libguile-program.texi 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796
  1. @c -*-texinfo-*-
  2. @c This is part of the GNU Guile Reference Manual.
  3. @c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2005, 2014
  4. @c Free Software Foundation, Inc.
  5. @c See the file guile.texi for copying conditions.
  6. @node Programming Overview
  7. @section An Overview of Guile Programming
  8. Guile is designed as an extension language interpreter that is
  9. straightforward to integrate with applications written in C (and C++).
  10. The big win here for the application developer is that Guile
  11. integration, as the Guile web page says, ``lowers your project's
  12. hacktivation energy.'' Lowering the hacktivation energy means that you,
  13. as the application developer, @emph{and your users}, reap the benefits
  14. that flow from being able to extend the application in a high level
  15. extension language rather than in plain old C.
  16. In abstract terms, it's difficult to explain what this really means and
  17. what the integration process involves, so instead let's begin by jumping
  18. straight into an example of how you might integrate Guile into an
  19. existing program, and what you could expect to gain by so doing. With
  20. that example under our belts, we'll then return to a more general
  21. analysis of the arguments involved and the range of programming options
  22. available.
  23. @menu
  24. * Extending Dia:: How one might extend Dia using Guile.
  25. * Scheme vs C:: Why Scheme is more hackable than C.
  26. * Testbed Example:: Example: using Guile in a testbed.
  27. * Programming Options:: Options for Guile programming.
  28. * User Programming:: How about application users?
  29. @end menu
  30. @node Extending Dia
  31. @subsection How One Might Extend Dia Using Guile
  32. Dia is a free software program for drawing schematic diagrams like flow
  33. charts and floor plans (@uref{http://www.gnome.org/projects/dia/}).
  34. This section conducts the thought
  35. experiment of adding Guile to Dia. In so doing, it aims to illustrate
  36. several of the steps and considerations involved in adding Guile to
  37. applications in general.
  38. @menu
  39. * Dia Objective:: Deciding why you want to add Guile.
  40. * Dia Steps:: Four steps required to add Guile.
  41. * Dia Objects:: How to represent Dia data in Scheme.
  42. * Dia Primitives:: Writing Guile primitives for Dia.
  43. * Dia Hook:: Providing a hook for Scheme evaluation.
  44. * Dia Structure:: Overall structure for adding Guile.
  45. * Dia Advanced:: Going further with Dia and Guile.
  46. @end menu
  47. @node Dia Objective
  48. @subsubsection Deciding Why You Want to Add Guile
  49. First off, you should understand why you want to add Guile to Dia at
  50. all, and that means forming a picture of what Dia does and how it does
  51. it. So, what are the constituents of the Dia application?
  52. @itemize @bullet
  53. @item
  54. Most importantly, the @dfn{application domain objects} --- in other
  55. words, the concepts that differentiate Dia from another application such
  56. as a word processor or spreadsheet: shapes, templates, connectors,
  57. pages, plus the properties of all these things.
  58. @item
  59. The code that manages the graphical face of the application, including
  60. the layout and display of the objects above.
  61. @item
  62. The code that handles input events, which indicate that the application
  63. user is wanting to do something.
  64. @end itemize
  65. @noindent
  66. (In other words, a textbook example of the @dfn{model - view -
  67. controller} paradigm.)
  68. Next question: how will Dia benefit once the Guile integration is
  69. complete? Several (positive!) answers are possible here, and the choice
  70. is obviously up to the application developers. Still, one answer is
  71. that the main benefit will be the ability to manipulate Dia's
  72. application domain objects from Scheme.
  73. Suppose that Dia made a set of procedures available in Scheme,
  74. representing the most basic operations on objects such as shapes,
  75. connectors, and so on. Using Scheme, the application user could then
  76. write code that builds upon these basic operations to create more
  77. complex procedures. For example, given basic procedures to enumerate
  78. the objects on a page, to determine whether an object is a square, and
  79. to change the fill pattern of a single shape, the user can write a
  80. Scheme procedure to change the fill pattern of all squares on the
  81. current page:
  82. @lisp
  83. (define (change-squares'-fill-pattern new-pattern)
  84. (for-each-shape current-page
  85. (lambda (shape)
  86. (if (square? shape)
  87. (change-fill-pattern shape new-pattern)))))
  88. @end lisp
  89. @node Dia Steps
  90. @subsubsection Four Steps Required to Add Guile
  91. Assuming this objective, four steps are needed to achieve it.
  92. First, you need a way of representing your application-specific objects
  93. --- such as @code{shape} in the previous example --- when they are
  94. passed into the Scheme world. Unless your objects are so simple that
  95. they map naturally into builtin Scheme data types like numbers and
  96. strings, you will probably want to use Guile's @dfn{foreign object}
  97. interface to create a new Scheme data type for your objects.
  98. Second, you need to write code for the basic operations like
  99. @code{for-each-shape} and @code{square?} such that they access and
  100. manipulate your existing data structures correctly, and then make these
  101. operations available as @dfn{primitives} on the Scheme level.
  102. Third, you need to provide some mechanism within the Dia application
  103. that a user can hook into to cause arbitrary Scheme code to be
  104. evaluated.
  105. Finally, you need to restructure your top-level application C code a
  106. little so that it initializes the Guile interpreter correctly and
  107. declares your @dfn{foreign objects} and @dfn{primitives} to the Scheme
  108. world.
  109. The following subsections expand on these four points in turn.
  110. @node Dia Objects
  111. @subsubsection How to Represent Dia Data in Scheme
  112. For all but the most trivial applications, you will probably want to
  113. allow some representation of your domain objects to exist on the Scheme
  114. level. This is where foreign objects come in, and with them issues of
  115. lifetime management and garbage collection.
  116. To get more concrete about this, let's look again at the example we gave
  117. earlier of how application users can use Guile to build higher-level
  118. functions from the primitives that Dia itself provides.
  119. @lisp
  120. (define (change-squares'-fill-pattern new-pattern)
  121. (for-each-shape current-page
  122. (lambda (shape)
  123. (if (square? shape)
  124. (change-fill-pattern shape new-pattern)))))
  125. @end lisp
  126. Consider what is stored here in the variable @code{shape}. For each
  127. shape on the current page, the @code{for-each-shape} primitive calls
  128. @code{(lambda (shape) @dots{})} with an argument representing that
  129. shape. Question is: how is that argument represented on the Scheme
  130. level? The issues are as follows.
  131. @itemize @bullet
  132. @item
  133. Whatever the representation, it has to be decodable again by the C code
  134. for the @code{square?} and @code{change-fill-pattern} primitives. In
  135. other words, a primitive like @code{square?} has somehow to be able to
  136. turn the value that it receives back into something that points to the
  137. underlying C structure describing a shape.
  138. @item
  139. The representation must also cope with Scheme code holding on to the
  140. value for later use. What happens if the Scheme code stores
  141. @code{shape} in a global variable, but then that shape is deleted (in a
  142. way that the Scheme code is not aware of), and later on some other
  143. Scheme code uses that global variable again in a call to, say,
  144. @code{square?}?
  145. @item
  146. The lifetime and memory allocation of objects that exist @emph{only} in
  147. the Scheme world is managed automatically by Guile's garbage collector
  148. using one simple rule: when there are no remaining references to an
  149. object, the object is considered dead and so its memory is freed. But
  150. for objects that exist in both C and Scheme, the picture is more
  151. complicated; in the case of Dia, where the @code{shape} argument passes
  152. transiently in and out of the Scheme world, it would be quite wrong the
  153. @strong{delete} the underlying C shape just because the Scheme code has
  154. finished evaluation. How do we avoid this happening?
  155. @end itemize
  156. One resolution of these issues is for the Scheme-level representation of
  157. a shape to be a new, Scheme-specific C structure wrapped up as a foreign
  158. object. The foreign object is what is passed into and out of Scheme
  159. code, and the Scheme-specific C structure inside the foreign object
  160. points to Dia's underlying C structure so that the code for primitives
  161. like @code{square?} can get at it.
  162. To cope with an underlying shape being deleted while Scheme code is
  163. still holding onto a Scheme shape value, the underlying C structure
  164. should have a new field that points to the Scheme-specific foreign
  165. object. When a shape is deleted, the relevant code chains through to
  166. the Scheme-specific structure and sets its pointer back to the
  167. underlying structure to NULL. Thus the foreign object value for the
  168. shape continues to exist, but any primitive code that tries to use it
  169. will detect that the underlying shape has been deleted because the
  170. underlying structure pointer is NULL.
  171. So, to summarize the steps involved in this resolution of the problem
  172. (and assuming that the underlying C structure for a shape is
  173. @code{struct dia_shape}):
  174. @itemize @bullet
  175. @item
  176. Define a new Scheme-specific structure that @emph{points} to the
  177. underlying C structure:
  178. @lisp
  179. struct dia_guile_shape
  180. @{
  181. struct dia_shape * c_shape; /* NULL => deleted */
  182. @}
  183. @end lisp
  184. @item
  185. Add a field to @code{struct dia_shape} that points to its @code{struct
  186. dia_guile_shape} if it has one ---
  187. @lisp
  188. struct dia_shape
  189. @{
  190. @dots{}
  191. struct dia_guile_shape * guile_shape;
  192. @}
  193. @end lisp
  194. @noindent
  195. --- so that C code can set @code{guile_shape->c_shape} to NULL when the
  196. underlying shape is deleted.
  197. @item
  198. Wrap @code{struct dia_guile_shape} as a foreign object type.
  199. @item
  200. Whenever you need to represent a C shape onto the Scheme level, create a
  201. foreign object instance for it, and pass that.
  202. @item
  203. In primitive code that receives a shape foreign object instance, check the
  204. @code{c_shape} field when decoding it, to find out whether the
  205. underlying C shape is still there.
  206. @end itemize
  207. As far as memory management is concerned, the foreign object values and
  208. their Scheme-specific structures are under the control of the garbage
  209. collector, whereas the underlying C structures are explicitly managed in
  210. exactly the same way that Dia managed them before we thought of adding
  211. Guile.
  212. When the garbage collector decides to free a shape foreign object value,
  213. it calls the @dfn{finalizer} function that was specified when defining
  214. the shape foreign object type. To maintain the correctness of the
  215. @code{guile_shape} field in the underlying C structure, this function
  216. should chain through to the underlying C structure (if it still exists)
  217. and set its @code{guile_shape} field to NULL.
  218. For full documentation on defining and using foreign object types, see
  219. @ref{Defining New Foreign Object Types}.
  220. @node Dia Primitives
  221. @subsubsection Writing Guile Primitives for Dia
  222. Once the details of object representation are decided, writing the
  223. primitive function code that you need is usually straightforward.
  224. A primitive is simply a C function whose arguments and return value are
  225. all of type @code{SCM}, and whose body does whatever you want it to do.
  226. As an example, here is a possible implementation of the @code{square?}
  227. primitive:
  228. @lisp
  229. static SCM square_p (SCM shape)
  230. @{
  231. struct dia_guile_shape * guile_shape;
  232. /* Check that arg is really a shape object. */
  233. scm_assert_foreign_object_type (shape_type, shape);
  234. /* Access Scheme-specific shape structure. */
  235. guile_shape = scm_foreign_object_ref (shape, 0);
  236. /* Find out if underlying shape exists and is a
  237. square; return answer as a Scheme boolean. */
  238. return scm_from_bool (guile_shape->c_shape &&
  239. (guile_shape->c_shape->type == DIA_SQUARE));
  240. @}
  241. @end lisp
  242. Notice how easy it is to chain through from the @code{SCM shape}
  243. parameter that @code{square_p} receives --- which is a foreign object
  244. --- to the Scheme-specific structure inside the foreign object, and
  245. thence to the underlying C structure for the shape.
  246. In this code, @code{scm_assert_foreign_object_type},
  247. @code{scm_foreign_object_ref}, and @code{scm_from_bool} are from the
  248. standard Guile API. We assume that @code{shape_type} was given to us
  249. when we made the shape foreign object type, using
  250. @code{scm_make_foreign_object_type}. The call to
  251. @code{scm_assert_foreign_object_type} ensures that @var{shape} is indeed
  252. a shape. This is needed to guard against Scheme code using the
  253. @code{square?} procedure incorrectly, as in @code{(square? "hello")};
  254. Scheme's latent typing means that usage errors like this must be caught
  255. at run time.
  256. Having written the C code for your primitives, you need to make them
  257. available as Scheme procedures by calling the @code{scm_c_define_gsubr}
  258. function. @code{scm_c_define_gsubr} (@pxref{Primitive Procedures})
  259. takes arguments that specify the Scheme-level name for the primitive and
  260. how many required, optional and rest arguments it can accept. The
  261. @code{square?} primitive always requires exactly one argument, so the
  262. call to make it available in Scheme reads like this:
  263. @lisp
  264. scm_c_define_gsubr ("square?", 1, 0, 0, square_p);
  265. @end lisp
  266. For where to put this call, see the subsection after next on the
  267. structure of Guile-enabled code (@pxref{Dia Structure}).
  268. @node Dia Hook
  269. @subsubsection Providing a Hook for the Evaluation of Scheme Code
  270. To make the Guile integration useful, you have to design some kind of
  271. hook into your application that application users can use to cause their
  272. Scheme code to be evaluated.
  273. Technically, this is straightforward; you just have to decide on a
  274. mechanism that is appropriate for your application. Think of Emacs, for
  275. example: when you type @kbd{@key{ESC} :}, you get a prompt where you can
  276. type in any Elisp code, which Emacs will then evaluate. Or, again like
  277. Emacs, you could provide a mechanism (such as an init file) to allow
  278. Scheme code to be associated with a particular key sequence, and
  279. evaluate the code when that key sequence is entered.
  280. In either case, once you have the Scheme code that you want to evaluate,
  281. as a null terminated string, you can tell Guile to evaluate it by
  282. calling the @code{scm_c_eval_string} function.
  283. @node Dia Structure
  284. @subsubsection Top-level Structure of Guile-enabled Dia
  285. Let's assume that the pre-Guile Dia code looks structurally like this:
  286. @itemize @bullet
  287. @item
  288. @code{main ()}
  289. @itemize @bullet
  290. @item
  291. do lots of initialization and setup stuff
  292. @item
  293. enter Gtk main loop
  294. @end itemize
  295. @end itemize
  296. When you add Guile to a program, one (rather technical) requirement is
  297. that Guile's garbage collector needs to know where the bottom of the C
  298. stack is. The easiest way to ensure this is to use
  299. @code{scm_boot_guile} like this:
  300. @itemize @bullet
  301. @item
  302. @code{main ()}
  303. @itemize @bullet
  304. @item
  305. do lots of initialization and setup stuff
  306. @item
  307. @code{scm_boot_guile (argc, argv, inner_main, NULL)}
  308. @end itemize
  309. @item
  310. @code{inner_main ()}
  311. @itemize @bullet
  312. @item
  313. define all foreign object types
  314. @item
  315. export primitives to Scheme using @code{scm_c_define_gsubr}
  316. @item
  317. enter Gtk main loop
  318. @end itemize
  319. @end itemize
  320. In other words, you move the guts of what was previously in your
  321. @code{main} function into a new function called @code{inner_main}, and
  322. then add a @code{scm_boot_guile} call, with @code{inner_main} as a
  323. parameter, to the end of @code{main}.
  324. Assuming that you are using foreign objects and have written primitive
  325. code as described in the preceding subsections, you also need to insert
  326. calls to declare your new foreign objects and export the primitives to
  327. Scheme. These declarations must happen @emph{inside} the dynamic scope
  328. of the @code{scm_boot_guile} call, but also @emph{before} any code is
  329. run that could possibly use them --- the beginning of @code{inner_main}
  330. is an ideal place for this.
  331. @node Dia Advanced
  332. @subsubsection Going Further with Dia and Guile
  333. The steps described so far implement an initial Guile integration that
  334. already gives a lot of additional power to Dia application users. But
  335. there are further steps that you could take, and it's interesting to
  336. consider a few of these.
  337. In general, you could progressively move more of Dia's source code from
  338. C into Scheme. This might make the code more maintainable and
  339. extensible, and it could open the door to new programming paradigms that
  340. are tricky to effect in C but straightforward in Scheme.
  341. A specific example of this is that you could use the guile-gtk package,
  342. which provides Scheme-level procedures for most of the Gtk+ library, to
  343. move the code that lays out and displays Dia objects from C to Scheme.
  344. As you follow this path, it naturally becomes less useful to maintain a
  345. distinction between Dia's original non-Guile-related source code, and
  346. its later code implementing foreign objects and primitives for the
  347. Scheme world.
  348. For example, suppose that the original source code had a
  349. @code{dia_change_fill_pattern} function:
  350. @lisp
  351. void dia_change_fill_pattern (struct dia_shape * shape,
  352. struct dia_pattern * pattern)
  353. @{
  354. /* real pattern change work */
  355. @}
  356. @end lisp
  357. During initial Guile integration, you add a @code{change_fill_pattern}
  358. primitive for Scheme purposes, which accesses the underlying structures
  359. from its foreign object values and uses @code{dia_change_fill_pattern}
  360. to do the real work:
  361. @lisp
  362. SCM change_fill_pattern (SCM shape, SCM pattern)
  363. @{
  364. struct dia_shape * d_shape;
  365. struct dia_pattern * d_pattern;
  366. @dots{}
  367. dia_change_fill_pattern (d_shape, d_pattern);
  368. return SCM_UNSPECIFIED;
  369. @}
  370. @end lisp
  371. At this point, it makes sense to keep @code{dia_change_fill_pattern} and
  372. @code{change_fill_pattern} separate, because
  373. @code{dia_change_fill_pattern} can also be called without going through
  374. Scheme at all, say because the user clicks a button which causes a
  375. C-registered Gtk+ callback to be called.
  376. But, if the code for creating buttons and registering their callbacks is
  377. moved into Scheme (using guile-gtk), it may become true that
  378. @code{dia_change_fill_pattern} can no longer be called other than
  379. through Scheme. In which case, it makes sense to abolish it and move
  380. its contents directly into @code{change_fill_pattern}, like this:
  381. @lisp
  382. SCM change_fill_pattern (SCM shape, SCM pattern)
  383. @{
  384. struct dia_shape * d_shape;
  385. struct dia_pattern * d_pattern;
  386. @dots{}
  387. /* real pattern change work */
  388. return SCM_UNSPECIFIED;
  389. @}
  390. @end lisp
  391. So further Guile integration progressively @emph{reduces} the amount of
  392. functional C code that you have to maintain over the long term.
  393. A similar argument applies to data representation. In the discussion of
  394. foreign objects earlier, issues arose because of the different memory
  395. management and lifetime models that normally apply to data structures in
  396. C and in Scheme. However, with further Guile integration, you can
  397. resolve this issue in a more radical way by allowing all your data
  398. structures to be under the control of the garbage collector, and kept
  399. alive by references from the Scheme world. Instead of maintaining an
  400. array or linked list of shapes in C, you would instead maintain a list
  401. in Scheme.
  402. Rather like the coalescing of @code{dia_change_fill_pattern} and
  403. @code{change_fill_pattern}, the practical upshot of such a change is
  404. that you would no longer have to keep the @code{dia_shape} and
  405. @code{dia_guile_shape} structures separate, and so wouldn't need to
  406. worry about the pointers between them. Instead, you could change the
  407. foreign object definition to wrap the @code{dia_shape} structure
  408. directly, and send @code{dia_guile_shape} off to the scrap yard. Cut
  409. out the middle man!
  410. Finally, we come to the holy grail of Guile's free software / extension
  411. language approach. Once you have a Scheme representation for
  412. interesting Dia data types like shapes, and a handy bunch of primitives
  413. for manipulating them, it suddenly becomes clear that you have a bundle
  414. of functionality that could have far-ranging use beyond Dia itself. In
  415. other words, the data types and primitives could now become a library,
  416. and Dia becomes just one of the many possible applications using that
  417. library --- albeit, at this early stage, a rather important one!
  418. In this model, Guile becomes just the glue that binds everything
  419. together. Imagine an application that usefully combined functionality
  420. from Dia, Gnumeric and GnuCash --- it's tricky right now, because no
  421. such application yet exists; but it'll happen some day @dots{}
  422. @node Scheme vs C
  423. @subsection Why Scheme is More Hackable Than C
  424. Underlying Guile's value proposition is the assumption that programming
  425. in a high level language, specifically Guile's implementation of Scheme,
  426. is necessarily better in some way than programming in C. What do we
  427. mean by this claim, and how can we be so sure?
  428. One class of advantages applies not only to Scheme, but more generally
  429. to any interpretable, high level, scripting language, such as Emacs
  430. Lisp, Python, Ruby, or @TeX{}'s macro language. Common features of all
  431. such languages, when compared to C, are that:
  432. @itemize @bullet
  433. @item
  434. They lend themselves to rapid and experimental development cycles,
  435. owing usually to a combination of their interpretability and the
  436. integrated development environment in which they are used.
  437. @item
  438. They free developers from some of the low level bookkeeping tasks
  439. associated with C programming, notably memory management.
  440. @item
  441. They provide high level features such as container objects and exception
  442. handling that make common programming tasks easier.
  443. @end itemize
  444. In the case of Scheme, particular features that make programming easier
  445. --- and more fun! --- are its powerful mechanisms for abstracting parts
  446. of programs (closures --- @pxref{About Closure}) and for iteration
  447. (@pxref{while do}).
  448. The evidence in support of this argument is empirical: the huge amount
  449. of code that has been written in extension languages for applications
  450. that support this mechanism. Most notable are extensions written in
  451. Emacs Lisp for GNU Emacs, in @TeX{}'s macro language for @TeX{}, and in
  452. Script-Fu for the Gimp, but there is increasingly now a significant code
  453. eco-system for Guile-based applications as well, such as Lilypond and
  454. GnuCash. It is close to inconceivable that similar amounts of
  455. functionality could have been added to these applications just by
  456. writing new code in their base implementation languages.
  457. @node Testbed Example
  458. @subsection Example: Using Guile for an Application Testbed
  459. As an example of what this means in practice, imagine writing a testbed
  460. for an application that is tested by submitting various requests (via a
  461. C interface) and validating the output received. Suppose further that
  462. the application keeps an idea of its current state, and that the
  463. ``correct'' output for a given request may depend on the current
  464. application state. A complete ``white box''@footnote{A @dfn{white box}
  465. test plan is one that incorporates knowledge of the internal design of
  466. the application under test.} test plan for this application would aim to
  467. submit all possible requests in each distinguishable state, and validate
  468. the output for all request/state combinations.
  469. To write all this test code in C would be very tedious. Suppose instead
  470. that the testbed code adds a single new C function, to submit an
  471. arbitrary request and return the response, and then uses Guile to export
  472. this function as a Scheme procedure. The rest of the testbed can then
  473. be written in Scheme, and so benefits from all the advantages of
  474. programming in Scheme that were described in the previous section.
  475. (In this particular example, there is an additional benefit of writing
  476. most of the testbed in Scheme. A common problem for white box testing
  477. is that mistakes and mistaken assumptions in the application under test
  478. can easily be reproduced in the testbed code. It is more difficult to
  479. copy mistakes like this when the testbed is written in a different
  480. language from the application.)
  481. @node Programming Options
  482. @subsection A Choice of Programming Options
  483. The preceding arguments and example point to a model of Guile
  484. programming that is applicable in many cases. According to this model,
  485. Guile programming involves a balance between C and Scheme programming,
  486. with the aim being to extract the greatest possible Scheme level benefit
  487. from the least amount of C level work.
  488. The C level work required in this model usually consists of packaging
  489. and exporting functions and application objects such that they can be
  490. seen and manipulated on the Scheme level. To help with this, Guile's C
  491. language interface includes utility features that aim to make this kind
  492. of integration very easy for the application developer.
  493. This model, though, is really just one of a range of possible
  494. programming options. If all of the functionality that you need is
  495. available from Scheme, you could choose instead to write your whole
  496. application in Scheme (or one of the other high level languages that
  497. Guile supports through translation), and simply use Guile as an
  498. interpreter for Scheme. (In the future, we hope that Guile will also be
  499. able to compile Scheme code, so lessening the performance gap between C
  500. and Scheme code.) Or, at the other end of the C--Scheme scale, you
  501. could write the majority of your application in C, and only call out to
  502. Guile occasionally for specific actions such as reading a configuration
  503. file or executing a user-specified extension. The choices boil down to
  504. two basic questions:
  505. @itemize @bullet
  506. @item
  507. Which parts of the application do you write in C, and which in Scheme
  508. (or another high level translated language)?
  509. @item
  510. How do you design the interface between the C and Scheme parts of your
  511. application?
  512. @end itemize
  513. These are of course design questions, and the right design for any given
  514. application will always depend upon the particular requirements that you
  515. are trying to meet. In the context of Guile, however, there are some
  516. generally applicable considerations that can help you when designing
  517. your answers.
  518. @menu
  519. * Available Functionality:: What functionality is already available?
  520. * Basic Constraints:: Functional and performance constraints.
  521. * Style Choices:: Your preferred programming style.
  522. * Program Control:: What controls program execution?
  523. @end menu
  524. @node Available Functionality
  525. @subsubsection What Functionality is Already Available?
  526. Suppose, for the sake of argument, that you would prefer to write your
  527. whole application in Scheme. Then the API available to you consists of:
  528. @itemize @bullet
  529. @item
  530. standard Scheme
  531. @item
  532. plus the extensions to standard Scheme provided by
  533. Guile in its core distribution
  534. @item
  535. plus any additional functionality that you or others have packaged so
  536. that it can be loaded as a Guile Scheme module.
  537. @end itemize
  538. A module in the last category can either be a pure Scheme module --- in
  539. other words a collection of utility procedures coded in Scheme --- or a
  540. module that provides a Scheme interface to an extension library coded in
  541. C --- in other words a nice package where someone else has done the work
  542. of wrapping up some useful C code for you. The set of available modules
  543. is growing quickly and already includes such useful examples as
  544. @code{(gtk gtk)}, which makes Gtk+ drawing functions available in
  545. Scheme, and @code{(database postgres)}, which provides SQL access to a
  546. Postgres database.
  547. Given the growing collection of pre-existing modules, it is quite
  548. feasible that your application could be implemented by combining a
  549. selection of these modules together with new application code written in
  550. Scheme.
  551. If this approach is not enough, because the functionality that your
  552. application needs is not already available in this form, and it is
  553. impossible to write the new functionality in Scheme, you will need to
  554. write some C code. If the required function is already available in C
  555. (e.g.@: in a library), all you need is a little glue to connect it to the
  556. world of Guile. If not, you need both to write the basic code and to
  557. plumb it into Guile.
  558. In either case, two general considerations are important. Firstly, what
  559. is the interface by which the functionality is presented to the Scheme
  560. world? Does the interface consist only of function calls (for example,
  561. a simple drawing interface), or does it need to include @dfn{objects} of
  562. some kind that can be passed between C and Scheme and manipulated by
  563. both worlds. Secondly, how does the lifetime and memory management of
  564. objects in the C code relate to the garbage collection governed approach
  565. of Scheme objects? In the case where the basic C code is not already
  566. written, most of the difficulties of memory management can be avoided by
  567. using Guile's C interface features from the start.
  568. For the full documentation on writing C code for Guile and connecting
  569. existing C code to the Guile world, see @ref{Defining New
  570. Foreign Object Types}, @ref{Primitive Procedures}, and @ref{Foreign
  571. Function Interface}.
  572. @node Basic Constraints
  573. @subsubsection Functional and Performance Constraints
  574. @c REFFIXME
  575. @node Style Choices
  576. @subsubsection Your Preferred Programming Style
  577. @c REFFIXME
  578. @node Program Control
  579. @subsubsection What Controls Program Execution?
  580. @c REFFIXME
  581. @node User Programming
  582. @subsection How About Application Users?
  583. So far we have considered what Guile programming means for an
  584. application developer. But what if you are instead @emph{using} an
  585. existing Guile-based application, and want to know what your
  586. options are for programming and extending this application?
  587. The answer to this question varies from one application to another,
  588. because the options available depend inevitably on whether the
  589. application developer has provided any hooks for you to hang your own
  590. code on and, if there are such hooks, what they allow you to
  591. do.@footnote{Of course, in the world of free software, you always have
  592. the freedom to modify the application's source code to your own
  593. requirements. Here we are concerned with the extension options that the
  594. application has provided for without your needing to modify its source
  595. code.} For example@dots{}
  596. @itemize @bullet
  597. @item
  598. If the application permits you to load and execute any Guile code, the
  599. world is your oyster. You can extend the application in any way that
  600. you choose.
  601. @item
  602. A more cautious application might allow you to load and execute Guile
  603. code, but only in a @dfn{safe} environment, where the interface
  604. available is restricted by the application from the standard Guile API.
  605. @item
  606. Or a really fearful application might not provide a hook to really
  607. execute user code at all, but just use Scheme syntax as a convenient way
  608. for users to specify application data or configuration options.
  609. @end itemize
  610. In the last two cases, what you can do is, by definition, restricted by
  611. the application, and you should refer to the application's own manual to
  612. find out your options.
  613. The most well known example of the first case is Emacs, with its
  614. extension language Emacs Lisp: as well as being a text editor, Emacs
  615. supports the loading and execution of arbitrary Emacs Lisp code. The
  616. result of such openness has been dramatic: Emacs now benefits from
  617. user-contributed Emacs Lisp libraries that extend the basic editing
  618. function to do everything from reading news to psychoanalysis and
  619. playing adventure games. The only limitation is that extensions are
  620. restricted to the functionality provided by Emacs's built-in set of
  621. primitive operations. For example, you can interact and display data by
  622. manipulating the contents of an Emacs buffer, but you can't pop-up and
  623. draw a window with a layout that is totally different to the Emacs
  624. standard.
  625. This situation with a Guile application that supports the loading of
  626. arbitrary user code is similar, except perhaps even more so, because
  627. Guile also supports the loading of extension libraries written in C.
  628. This last point enables user code to add new primitive operations to
  629. Guile, and so to bypass the limitation present in Emacs Lisp.
  630. At this point, the distinction between an application developer and an
  631. application user becomes rather blurred. Instead of seeing yourself as
  632. a user extending an application, you could equally well say that you are
  633. developing a new application of your own using some of the primitive
  634. functionality provided by the original application. As such, all the
  635. discussions of the preceding sections of this chapter are relevant to
  636. how you can proceed with developing your extension.
  637. @c Local Variables:
  638. @c TeX-master: "guile.texi"
  639. @c End: