libguile-program.texi 31 KB

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