1This is guile.info, produced by makeinfo version 6.7 from guile.texi. 2 3This manual documents Guile version 3.0.7. 4 5 Copyright (C) 1996-1997, 2000-2005, 2009-2021 Free Software 6Foundation, Inc. 7 8 Permission is granted to copy, distribute and/or modify this document 9under the terms of the GNU Free Documentation License, Version 1.3 or 10any later version published by the Free Software Foundation; with no 11Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A 12copy of the license is included in the section entitled “GNU Free 13Documentation License.” 14INFO-DIR-SECTION The Algorithmic Language Scheme 15START-INFO-DIR-ENTRY 16* Guile Reference: (guile). The Guile reference manual. 17END-INFO-DIR-ENTRY 18 19 20File: guile.info, Node: Top, Next: Preface, Prev: (dir), Up: (dir) 21 22The Guile Reference Manual 23************************** 24 25This manual documents Guile version 3.0.7. 26 27 Copyright (C) 1996-1997, 2000-2005, 2009-2021 Free Software 28Foundation, Inc. 29 30 Permission is granted to copy, distribute and/or modify this document 31under the terms of the GNU Free Documentation License, Version 1.3 or 32any later version published by the Free Software Foundation; with no 33Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A 34copy of the license is included in the section entitled “GNU Free 35Documentation License.” 36 37* Menu: 38 39 40* Preface:: 41* Introduction:: 42 43* Hello Guile!:: 44* Hello Scheme!:: 45 46* Programming in Scheme:: 47* Programming in C:: 48 49* API Reference:: 50 51* Guile Modules:: 52 53* GOOPS:: 54 55* Guile Implementation:: 56 57Appendices 58 59* GNU Free Documentation License:: The license of this manual. 60 61Indices 62 63* Concept Index:: 64* Procedure Index:: 65* Variable Index:: 66* Type Index:: 67* R5RS Index:: 68 69 70File: guile.info, Node: Preface, Next: Introduction, Up: Top 71 72Preface 73******* 74 75This manual describes how to use Guile, GNU’s Ubiquitous Intelligent 76Language for Extensions. It relates particularly to Guile version 773.0.7. 78 79* Menu: 80 81* Contributors:: 82* Guile License:: 83 84 85File: guile.info, Node: Contributors, Next: Guile License, Up: Preface 86 87Contributors to this Manual 88=========================== 89 90Like Guile itself, the Guile reference manual is a living entity, cared 91for by many people over a long period of time. As such, it is hard to 92identify individuals of whom to say “yes, this single person wrote the 93manual.” 94 95 Still, among the many contributions, some caretakers stand out. 96First among them is Neil Jerram, who has worked on this document for 97over ten years. Neil’s attention both to detail and to the big picture 98have made a real difference in the understanding of a generation of 99Guile hackers. 100 101 Next we should note Marius Vollmer’s effect on this document. Marius 102maintained Guile during a period in which Guile’s API was clarified—put 103to the fire, so to speak—and he had the good sense to effect the same 104change on the manual. 105 106 Martin Grabmueller made substantial contributions throughout the 107manual in preparation for the Guile 1.6 release, including filling out a 108lot of the documentation of Scheme data types, control mechanisms and 109procedures. In addition, he wrote the documentation for Guile’s SRFI 110modules and modules associated with the Guile REPL. 111 112 Ludovic Courtès and Andy Wingo, who co-maintain Guile since 2010, 113along with Mark Weaver, have also made their dent in the manual, writing 114documentation for new modules and subsystems that arrived with Guile 1152.0. Ludovic, Andy, and Mark are also responsible for ensuring that the 116existing text retains its relevance as Guile evolves. *Note Reporting 117Bugs::, for more information on reporting problems in this manual. 118 119 The content for the first versions of this manual incorporated and 120was inspired by documents from Aubrey Jaffer, author of the SCM system 121on which Guile was based, and from Tom Lord, Guile’s first maintainer. 122Although most of this text has been rewritten, all of it was important, 123and some of the structure remains. 124 125 The manual for the first versions of Guile were largely written, 126edited, and compiled by Mark Galassi and Jim Blandy. In particular, Jim 127wrote the original tutorial on Guile’s data representation and the C API 128for accessing Guile objects. 129 130 Significant portions were also contributed by Thien-Thi Nguyen, Kevin 131Ryde, Mikael Djurfeldt, Christian Lynbech, Julian Graham, Gary Houston, 132Tim Pierce, and a few dozen more. You, reader, are most welcome to join 133their esteemed ranks. Visit Guile’s web site at 134<http://www.gnu.org/software/guile/> to find out how to get involved. 135 136 137File: guile.info, Node: Guile License, Prev: Contributors, Up: Preface 138 139The Guile License 140================= 141 142Guile is Free Software. Guile is copyrighted, not public domain, and 143there are restrictions on its distribution or redistribution, but these 144restrictions are designed to permit everything a cooperating person 145would want to do. 146 147 • The Guile library (libguile) and supporting files are published 148 under the terms of the GNU Lesser General Public License version 3 149 or later. See the files ‘COPYING.LESSER’ and ‘COPYING’. 150 151 • The Guile readline module is published under the terms of the GNU 152 General Public License version 3 or later. See the file ‘COPYING’. 153 154 • The manual you’re now reading is published under the terms of the 155 GNU Free Documentation License (*note GNU Free Documentation 156 License::). 157 158 C code linking to the Guile library is subject to terms of that 159library. Basically such code may be published on any terms, provided 160users can re-link against a new or modified version of Guile. 161 162 C code linking to the Guile readline module is subject to the terms 163of that module. Basically such code must be published on Free terms. 164 165 Scheme level code written to be run by Guile (but not derived from 166Guile itself) is not restricted in any way, and may be published on any 167terms. We encourage authors to publish on Free terms. 168 169 You must be aware there is no warranty whatsoever for Guile. This is 170described in full in the licenses. 171 172 173File: guile.info, Node: Introduction, Next: Hello Guile!, Prev: Preface, Up: Top 174 1751 Introduction 176************** 177 178Guile is an implementation of the Scheme programming language. Scheme 179(<http://schemers.org/>) is an elegant and conceptually simple dialect 180of Lisp, originated by Guy Steele and Gerald Sussman, and since evolved 181by the series of reports known as RnRS (the Revised^n Reports on 182Scheme). 183 184 Unlike, for example, Python or Perl, Scheme has no benevolent 185dictator. There are many Scheme implementations, with different 186characteristics and with communities and academic activities around 187them, and the language develops as a result of the interplay between 188these. Guile’s particular characteristics are that 189 190 • it is easy to combine with other code written in C 191 • it has a historical and continuing connection with the GNU Project 192 • it emphasizes interactive and incremental programming 193 • it actually supports several languages, not just Scheme. 194 195The next few sections explain what we mean by these points. The 196sections after that cover how you can obtain and install Guile, and the 197typographical conventions that we use in this manual. 198 199* Menu: 200 201* Guile and Scheme:: 202* Combining with C:: 203* Guile and the GNU Project:: 204* Interactive Programming:: 205* Supporting Multiple Languages:: 206* Obtaining and Installing Guile:: 207* Organisation of this Manual:: 208* Typographical Conventions:: 209 210 211File: guile.info, Node: Guile and Scheme, Next: Combining with C, Up: Introduction 212 2131.1 Guile and Scheme 214==================== 215 216Guile implements Scheme as described in the Revised^5 Report on the 217Algorithmic Language Scheme (usually known as R5RS), providing clean and 218general data and control structures. Guile goes beyond the rather 219austere language presented in R5RS, extending it with a module system, 220full access to POSIX system calls, networking support, multiple threads, 221dynamic linking, a foreign function call interface, powerful string 222processing, and many other features needed for programming in the real 223world. 224 225 In 2007, the Scheme community agreed upon and published R6RS, a 226significant installment in the RnRS series. R6RS expands the core 227Scheme language, and standardises many non-core functions that 228implementations—including Guile—have previously done in different ways. 229Over time, Guile has been updated to incorporate almost all of the 230features of R6RS, and to adjust some existing features to conform to the 231R6RS specification. *Note R6RS Support::, for full details. 232 233 In parallel to official standardization efforts, the SRFI process 234(<http://srfi.schemers.org/>) standardises interfaces for many practical 235needs, such as multithreaded programming and multidimensional arrays. 236Guile supports many SRFIs, as documented in detail in *note SRFI 237Support::. 238 239 The process that led to the R6RS standard brought a split in the 240Scheme community to the surface. The implementors that wrote R6RS 241considered that it was impossible to write useful, portable programs in 242R5RS, and that only an ambitious standard could solve this problem. 243However, part of the Scheme world saw the R6RS effort as too broad, and 244as having included some components that would never be adopted by more 245minimalistic Scheme implementations. This second group succeeded in 246taking control of the official Scheme standardization track and in 2013 247released a more limited R7RS, essentially consisting of R5RS, plus a 248module system. Guile supports R7RS also. *Note R7RS Support::. 249 250 With R6RS and R7RS, the unified Scheme standardization process 251appears to have more or less run its course. There will continue to be 252more code written in terms of both systems, and modules defined using 253the SRFI process, and Guile will support both. However for future 254directions, Guile takes inspiration from other related language 255communities: Racket, Clojure, Concurrent ML, and so on. 256 257 In summary, Guile supports writing and running code written to the 258R5RS, R6RS, and R7RS Scheme standards, and also supports a number of 259SRFI modules. However for most users, until a need for 260cross-implementation portability has been identified, we recommend using 261the parts of Guile that are useful in solving the problem at hand, 262regardless of whether they proceed from a standard or whether they are 263Guile-specific. 264 265 266File: guile.info, Node: Combining with C, Next: Guile and the GNU Project, Prev: Guile and Scheme, Up: Introduction 267 2681.2 Combining with C Code 269========================= 270 271Like a shell, Guile can run interactively—reading expressions from the 272user, evaluating them, and displaying the results—or as a script 273interpreter, reading and executing Scheme code from a file. Guile also 274provides an object library, “libguile”, that allows other applications 275to easily incorporate a complete Scheme interpreter. An application can 276then use Guile as an extension language, a clean and powerful 277configuration language, or as multi-purpose “glue”, connecting 278primitives provided by the application. It is easy to call Scheme code 279from C code and vice versa, giving the application designer full control 280of how and when to invoke the interpreter. Applications can add new 281functions, data types, control structures, and even syntax to Guile, 282creating a domain-specific language tailored to the task at hand, but 283based on a robust language design. 284 285 This kind of combination is helped by four aspects of Guile’s design 286and history. First is that Guile has always been targeted as an 287extension language. Hence its C API has always been of great 288importance, and has been developed accordingly. Second and third are 289rather technical points—that Guile uses conservative garbage collection, 290and that it implements the Scheme concept of continuations by copying 291and reinstating the C stack—but whose practical consequence is that most 292existing C code can be glued into Guile as is, without needing 293modifications to cope with strange Scheme execution flows. Last is the 294module system, which helps extensions to coexist without stepping on 295each others’ toes. 296 297 Guile’s module system allows one to break up a large program into 298manageable sections with well-defined interfaces between them. Modules 299may contain a mixture of interpreted and compiled code; Guile can use 300either static or dynamic linking to incorporate compiled code. Modules 301also encourage developers to package up useful collections of routines 302for general distribution; as of this writing, one can find Emacs 303interfaces, database access routines, compilers, GUI toolkit interfaces, 304and HTTP client functions, among others. 305 306 307File: guile.info, Node: Guile and the GNU Project, Next: Interactive Programming, Prev: Combining with C, Up: Introduction 308 3091.3 Guile and the GNU Project 310============================= 311 312Guile was conceived by the GNU Project following the fantastic success 313of Emacs Lisp as an extension language within Emacs. Just as Emacs Lisp 314allowed complete and unanticipated applications to be written within the 315Emacs environment, the idea was that Guile should do the same for other 316GNU Project applications. This remains true today. 317 318 The idea of extensibility is closely related to the GNU project’s 319primary goal, that of promoting software freedom. Software freedom 320means that people receiving a software package can modify or enhance it 321to their own desires, including in ways that may not have occurred at 322all to the software’s original developers. For programs written in a 323compiled language like C, this freedom covers modifying and rebuilding 324the C code; but if the program also provides an extension language, that 325is usually a much friendlier and lower-barrier-of-entry way for the user 326to start making their own changes. 327 328 Guile is now used by GNU project applications such as AutoGen, 329Lilypond, Denemo, Mailutils, TeXmacs and Gnucash, and we hope that there 330will be many more in future. 331 332 333File: guile.info, Node: Interactive Programming, Next: Supporting Multiple Languages, Prev: Guile and the GNU Project, Up: Introduction 334 3351.4 Interactive Programming 336=========================== 337 338Non-free software has no interest in its users being able to see how it 339works. They are supposed to just accept it, or to report problems and 340hope that the source code owners will choose to work on them. 341 342 Free software aims to work reliably just as much as non-free software 343does, but it should also empower its users by making its workings 344available. This is useful for many reasons, including education, 345auditing and enhancements, as well as for debugging problems. 346 347 The ideal free software system achieves this by making it easy for 348interested users to see the source code for a feature that they are 349using, and to follow through that source code step-by-step, as it runs. 350In Emacs, good examples of this are the source code hyperlinks in the 351help system, and ‘edebug’. Then, for bonus points and maximising the 352ability for the user to experiment quickly with code changes, the system 353should allow parts of the source code to be modified and reloaded into 354the running program, to take immediate effect. 355 356 Guile is designed for this kind of interactive programming, and this 357distinguishes it from many Scheme implementations that instead 358prioritise running a fixed Scheme program as fast as possible—because 359there are tradeoffs between performance and the ability to modify parts 360of an already running program. There are faster Schemes than Guile, but 361Guile is a GNU project and so prioritises the GNU vision of programming 362freedom and experimentation. 363 364 365File: guile.info, Node: Supporting Multiple Languages, Next: Obtaining and Installing Guile, Prev: Interactive Programming, Up: Introduction 366 3671.5 Supporting Multiple Languages 368================================= 369 370Since the 2.0 release, Guile’s architecture supports compiling any 371language to its core virtual machine bytecode, and Scheme is just one of 372the supported languages. Other supported languages are Emacs Lisp, 373ECMAScript (commonly known as Javascript) and Brainfuck, and work is 374under discussion for Lua, Ruby and Python. 375 376 This means that users can program applications which use Guile in the 377language of their choice, rather than having the tastes of the 378application’s author imposed on them. 379 380 381File: guile.info, Node: Obtaining and Installing Guile, Next: Organisation of this Manual, Prev: Supporting Multiple Languages, Up: Introduction 382 3831.6 Obtaining and Installing Guile 384================================== 385 386Guile can be obtained from the main GNU archive site <ftp://ftp.gnu.org> 387or any of its mirrors. The file will be named guile-VERSION.tar.gz. 388The current version is 3.0.7, so the file you should grab is: 389 390 <ftp://ftp.gnu.org/gnu/guile/guile-3.0.7.tar.gz> 391 392 To unbundle Guile use the instruction 393 394 zcat guile-3.0.7.tar.gz | tar xvf - 395 396which will create a directory called ‘guile-3.0.7’ with all the sources. 397You can look at the file ‘INSTALL’ for detailed instructions on how to 398build and install Guile, but you should be able to just do 399 400 cd guile-3.0.7 401 ./configure 402 make 403 make install 404 405 This will install the Guile executable ‘guile’, the Guile library 406‘libguile’ and various associated header files and support libraries. 407It will also install the Guile reference manual. 408 409 Since this manual frequently refers to the Scheme “standard”, also 410known as R5RS, or the “Revised^5 Report on the Algorithmic Language 411Scheme”, we have included the report in the Guile distribution; see 412*note Introduction: (r5rs)Top. This will also be installed in your info 413directory. 414 415 416File: guile.info, Node: Organisation of this Manual, Next: Typographical Conventions, Prev: Obtaining and Installing Guile, Up: Introduction 417 4181.7 Organisation of this Manual 419=============================== 420 421The rest of this manual is organised into the following chapters. 422 423*Chapter 2: Hello Guile!* 424 A whirlwind tour shows how Guile can be used interactively and as a 425 script interpreter, how to link Guile into your own applications, 426 and how to write modules of interpreted and compiled code for use 427 with Guile. Everything introduced here is documented again and in 428 full by the later parts of the manual. 429 430*Chapter 3: Hello Scheme!* 431 For readers new to Scheme, this chapter provides an introduction to 432 the basic ideas of the Scheme language. This material would apply 433 to any Scheme implementation and so does not make reference to 434 anything Guile-specific. 435 436*Chapter 4: Programming in Scheme* 437 Provides an overview of programming in Scheme with Guile. It 438 covers how to invoke the ‘guile’ program from the command-line and 439 how to write scripts in Scheme. It also introduces the extensions 440 that Guile offers beyond standard Scheme. 441 442*Chapter 5: Programming in C* 443 Provides an overview of how to use Guile in a C program. It 444 discusses the fundamental concepts that you need to understand to 445 access the features of Guile, such as dynamic types and the garbage 446 collector. It explains in a tutorial like manner how to define new 447 data types and functions for the use by Scheme programs. 448 449*Chapter 6: Guile API Reference* 450 This part of the manual documents the Guile API in 451 functionality-based groups with the Scheme and C interfaces 452 presented side by side. 453 454*Chapter 7: Guile Modules* 455 Describes some important modules, distributed as part of the Guile 456 distribution, that extend the functionality provided by the Guile 457 Scheme core. 458 459*Chapter 8: GOOPS* 460 Describes GOOPS, an object oriented extension to Guile that 461 provides classes, multiple inheritance and generic functions. 462 463 464File: guile.info, Node: Typographical Conventions, Prev: Organisation of this Manual, Up: Introduction 465 4661.8 Typographical Conventions 467============================= 468 469In examples and procedure descriptions and all other places where the 470evaluation of Scheme expression is shown, we use some notation for 471denoting the output and evaluation results of expressions. 472 473 The symbol ‘⇒’ is used to tell which value is returned by an 474evaluation: 475 476 (+ 1 2) 477 ⇒ 3 478 479 Some procedures produce some output besides returning a value. This 480is denoted by the symbol ‘⊣’. 481 482 (begin (display 1) (newline) 'hooray) 483 ⊣ 1 484 ⇒ hooray 485 486 As you can see, this code prints ‘1’ (denoted by ‘⊣’), and returns 487‘hooray’ (denoted by ‘⇒’). 488 489 490File: guile.info, Node: Hello Guile!, Next: Hello Scheme!, Prev: Introduction, Up: Top 491 4922 Hello Guile! 493************** 494 495This chapter presents a quick tour of all the ways that Guile can be 496used. There are additional examples in the ‘examples/’ directory in the 497Guile source distribution. It also explains how best to report any 498problems that you find. 499 500 The following examples assume that Guile has been installed in 501‘/usr/local/’. 502 503* Menu: 504 505* Running Guile Interactively:: 506* Running Guile Scripts:: 507* Linking Guile into Programs:: 508* Writing Guile Extensions:: 509* Using the Guile Module System:: 510* Reporting Bugs:: 511 512 513File: guile.info, Node: Running Guile Interactively, Next: Running Guile Scripts, Up: Hello Guile! 514 5152.1 Running Guile Interactively 516=============================== 517 518In its simplest form, Guile acts as an interactive interpreter for the 519Scheme programming language, reading and evaluating Scheme expressions 520the user enters from the terminal. Here is a sample interaction between 521Guile and a user; the user’s input appears after the ‘$’ and 522‘scheme@(guile-user)>’ prompts: 523 524 $ guile 525 scheme@(guile-user)> (+ 1 2 3) ; add some numbers 526 $1 = 6 527 scheme@(guile-user)> (define (factorial n) ; define a function 528 (if (zero? n) 1 (* n (factorial (- n 1))))) 529 scheme@(guile-user)> (factorial 20) 530 $2 = 2432902008176640000 531 scheme@(guile-user)> (getpwnam "root") ; look in /etc/passwd 532 $3 = #("root" "x" 0 0 "root" "/root" "/bin/bash") 533 scheme@(guile-user)> C-d 534 $ 535 536 537File: guile.info, Node: Running Guile Scripts, Next: Linking Guile into Programs, Prev: Running Guile Interactively, Up: Hello Guile! 538 5392.2 Running Guile Scripts 540========================= 541 542Like AWK, Perl, or any shell, Guile can interpret script files. A Guile 543script is simply a file of Scheme code with some extra information at 544the beginning which tells the operating system how to invoke Guile, and 545then tells Guile how to handle the Scheme code. 546 547 Here is a trivial Guile script. *Note Guile Scripting::, for more 548details. 549 550 #!/usr/local/bin/guile -s 551 !# 552 (display "Hello, world!") 553 (newline) 554 555 556File: guile.info, Node: Linking Guile into Programs, Next: Writing Guile Extensions, Prev: Running Guile Scripts, Up: Hello Guile! 557 5582.3 Linking Guile into Programs 559=============================== 560 561The Guile interpreter is available as an object library, to be linked 562into applications using Scheme as a configuration or extension language. 563 564 Here is ‘simple-guile.c’, source code for a program that will produce 565a complete Guile interpreter. In addition to all usual functions 566provided by Guile, it will also offer the function ‘my-hostname’. 567 568 #include <stdlib.h> 569 #include <libguile.h> 570 571 static SCM 572 my_hostname (void) 573 { 574 char *s = getenv ("HOSTNAME"); 575 if (s == NULL) 576 return SCM_BOOL_F; 577 else 578 return scm_from_locale_string (s); 579 } 580 581 static void 582 inner_main (void *data, int argc, char **argv) 583 { 584 scm_c_define_gsubr ("my-hostname", 0, 0, 0, my_hostname); 585 scm_shell (argc, argv); 586 } 587 588 int 589 main (int argc, char **argv) 590 { 591 scm_boot_guile (argc, argv, inner_main, 0); 592 return 0; /* never reached */ 593 } 594 595 When Guile is correctly installed on your system, the above program 596can be compiled and linked like this: 597 598 $ gcc -o simple-guile simple-guile.c \ 599 `pkg-config --cflags --libs guile-3.0` 600 601 When it is run, it behaves just like the ‘guile’ program except that 602you can also call the new ‘my-hostname’ function. 603 604 $ ./simple-guile 605 scheme@(guile-user)> (+ 1 2 3) 606 $1 = 6 607 scheme@(guile-user)> (my-hostname) 608 "burns" 609 610 611File: guile.info, Node: Writing Guile Extensions, Next: Using the Guile Module System, Prev: Linking Guile into Programs, Up: Hello Guile! 612 6132.4 Writing Guile Extensions 614============================ 615 616You can link Guile into your program and make Scheme available to the 617users of your program. You can also link your library into Guile and 618make its functionality available to all users of Guile. 619 620 A library that is linked into Guile is called an “extension”, but it 621really just is an ordinary object library. 622 623 The following example shows how to write a simple extension for Guile 624that makes the ‘j0’ function available to Scheme code. 625 626 #include <math.h> 627 #include <libguile.h> 628 629 SCM 630 j0_wrapper (SCM x) 631 { 632 return scm_from_double (j0 (scm_to_double (x))); 633 } 634 635 void 636 init_bessel () 637 { 638 scm_c_define_gsubr ("j0", 1, 0, 0, j0_wrapper); 639 } 640 641 This C source file needs to be compiled into a shared library. Here 642is how to do it on GNU/Linux: 643 644 gcc `pkg-config --cflags guile-3.0` \ 645 -shared -o libguile-bessel.so -fPIC bessel.c 646 647 For creating shared libraries portably, we recommend the use of GNU 648Libtool (*note Introduction: (libtool)Top.). 649 650 A shared library can be loaded into a running Guile process with the 651function ‘load-extension’. The ‘j0’ is then immediately available: 652 653 $ guile 654 scheme@(guile-user)> (load-extension "./libguile-bessel" "init_bessel") 655 scheme@(guile-user)> (j0 2) 656 $1 = 0.223890779141236 657 658 For more on how to install your extension, *note Installing Site 659Packages::. 660 661 662File: guile.info, Node: Using the Guile Module System, Next: Reporting Bugs, Prev: Writing Guile Extensions, Up: Hello Guile! 663 6642.5 Using the Guile Module System 665================================= 666 667Guile has support for dividing a program into “modules”. By using 668modules, you can group related code together and manage the composition 669of complete programs from largely independent parts. 670 671 For more details on the module system beyond this introductory 672material, *Note Modules::. 673 674* Menu: 675 676* Using Modules:: 677* Writing new Modules:: 678* Putting Extensions into Modules:: 679 680 681File: guile.info, Node: Using Modules, Next: Writing new Modules, Up: Using the Guile Module System 682 6832.5.1 Using Modules 684------------------- 685 686Guile comes with a lot of useful modules, for example for string 687processing or command line parsing. Additionally, there exist many 688Guile modules written by other Guile hackers, but which have to be 689installed manually. 690 691 Here is a sample interactive session that shows how to use the 692‘(ice-9 popen)’ module which provides the means for communicating with 693other processes over pipes together with the ‘(ice-9 rdelim)’ module 694that provides the function ‘read-line’. 695 696 $ guile 697 scheme@(guile-user)> (use-modules (ice-9 popen)) 698 scheme@(guile-user)> (use-modules (ice-9 rdelim)) 699 scheme@(guile-user)> (define p (open-input-pipe "ls -l")) 700 scheme@(guile-user)> (read-line p) 701 $1 = "total 30" 702 scheme@(guile-user)> (read-line p) 703 $2 = "drwxr-sr-x 2 mgrabmue mgrabmue 1024 Mar 29 19:57 CVS" 704 705 706File: guile.info, Node: Writing new Modules, Next: Putting Extensions into Modules, Prev: Using Modules, Up: Using the Guile Module System 707 7082.5.2 Writing new Modules 709------------------------- 710 711You can create new modules using the syntactic form ‘define-module’. 712All definitions following this form until the next ‘define-module’ are 713placed into the new module. 714 715 One module is usually placed into one file, and that file is 716installed in a location where Guile can automatically find it. The 717following session shows a simple example. 718 719 $ cat /usr/local/share/guile/site/foo/bar.scm 720 721 (define-module (foo bar) 722 #:export (frob)) 723 724 (define (frob x) (* 2 x)) 725 726 $ guile 727 scheme@(guile-user)> (use-modules (foo bar)) 728 scheme@(guile-user)> (frob 12) 729 $1 = 24 730 731 For more on how to install your module, *note Installing Site 732Packages::. 733 734 735File: guile.info, Node: Putting Extensions into Modules, Prev: Writing new Modules, Up: Using the Guile Module System 736 7372.5.3 Putting Extensions into Modules 738------------------------------------- 739 740In addition to Scheme code you can also put things that are defined in C 741into a module. 742 743 You do this by writing a small Scheme file that defines the module 744and call ‘load-extension’ directly in the body of the module. 745 746 $ cat /usr/local/share/guile/site/math/bessel.scm 747 748 (define-module (math bessel) 749 #:export (j0)) 750 751 (load-extension "libguile-bessel" "init_bessel") 752 753 $ file /usr/local/lib/guile/3.0/extensions/libguile-bessel.so 754 ... ELF 32-bit LSB shared object ... 755 $ guile 756 scheme@(guile-user)> (use-modules (math bessel)) 757 scheme@(guile-user)> (j0 2) 758 $1 = 0.223890779141236 759 760 *Note Foreign Extensions::, for more information. 761 762 763File: guile.info, Node: Reporting Bugs, Prev: Using the Guile Module System, Up: Hello Guile! 764 7652.6 Reporting Bugs 766================== 767 768Any problems with the installation should be reported to 769<bug-guile@gnu.org>. 770 771 If you find a bug in Guile, please report it to the Guile developers, 772so they can fix it. They may also be able to suggest workarounds when 773it is not possible for you to apply the bug-fix or install a new version 774of Guile yourself. 775 776 Before sending in bug reports, please check with the following list 777that you really have found a bug. 778 779 • Whenever documentation and actual behavior differ, you have 780 certainly found a bug, either in the documentation or in the 781 program. 782 783 • When Guile crashes, it is a bug. 784 785 • When Guile hangs or takes forever to complete a task, it is a bug. 786 787 • When calculations produce wrong results, it is a bug. 788 789 • When Guile signals an error for valid Scheme programs, it is a bug. 790 791 • When Guile does not signal an error for invalid Scheme programs, it 792 may be a bug, unless this is explicitly documented. 793 794 • When some part of the documentation is not clear and does not make 795 sense to you even after re-reading the section, it is a bug. 796 797 Before reporting the bug, check whether any programs you have loaded 798into Guile, including your ‘.guile’ file, set any variables that may 799affect the functioning of Guile. Also, see whether the problem happens 800in a freshly started Guile without loading your ‘.guile’ file (start 801Guile with the ‘-q’ switch to prevent loading the init file). If the 802problem does _not_ occur then, you must report the precise contents of 803any programs that you must load into Guile in order to cause the problem 804to occur. 805 806 When you write a bug report, please make sure to include as much of 807the information described below in the report. If you can’t figure out 808some of the items, it is not a problem, but the more information we get, 809the more likely we can diagnose and fix the bug. 810 811 • The version number of Guile. You can get this information from 812 invoking ‘guile --version’ at your shell, or calling ‘(version)’ 813 from within Guile. 814 815 • Your machine type, as determined by the ‘config.guess’ shell 816 script. If you have a Guile checkout, this file is located in 817 ‘build-aux’; otherwise you can fetch the latest version from 818 <http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess;hb=HEAD>. 819 820 $ build-aux/config.guess 821 x86_64-unknown-linux-gnu 822 823 • If you installed Guile from a binary package, the version of that 824 package. On systems that use RPM, use ‘rpm -qa | grep guile’. On 825 systems that use DPKG, ‘dpkg -l | grep guile’. 826 827 • If you built Guile yourself, the build configuration that you used: 828 829 $ ./config.status --config 830 '--enable-error-on-warning' '--disable-deprecated'... 831 832 • A complete description of how to reproduce the bug. 833 834 If you have a Scheme program that produces the bug, please include 835 it in the bug report. If your program is too big to include, 836 please try to reduce your code to a minimal test case. 837 838 If you can reproduce your problem at the REPL, that is best. Give 839 a transcript of the expressions you typed at the REPL. 840 841 • A description of the incorrect behavior. For example, "The Guile 842 process gets a fatal signal," or, "The resulting output is as 843 follows, which I think is wrong." 844 845 If the manifestation of the bug is a Guile error message, it is 846 important to report the precise text of the error message, and a 847 backtrace showing how the Scheme program arrived at the error. 848 This can be done using the ‘,backtrace’ command in Guile’s 849 debugger. 850 851 If your bug causes Guile to crash, additional information from a 852low-level debugger such as GDB might be helpful. If you have built 853Guile yourself, you can run Guile under GDB via the 854‘meta/gdb-uninstalled-guile’ script. Instead of invoking Guile as 855usual, invoke the wrapper script, type ‘run’ to start the process, then 856‘backtrace’ when the crash comes. Include that backtrace in your 857report. 858 859 860File: guile.info, Node: Hello Scheme!, Next: Programming in Scheme, Prev: Hello Guile!, Up: Top 861 8623 Hello Scheme! 863*************** 864 865In this chapter, we introduce the basic concepts that underpin the 866elegance and power of the Scheme language. 867 868 Readers who already possess a background knowledge of Scheme may 869happily skip this chapter. For the reader who is new to the language, 870however, the following discussions on data, procedures, expressions and 871closure are designed to provide a minimum level of Scheme understanding 872that is more or less assumed by the chapters that follow. 873 874 The style of this introductory material aims about halfway between 875the terse precision of R5RS and the discursiveness of existing Scheme 876tutorials. For pointers to useful Scheme resources on the web, please 877see *note Further Reading::. 878 879* Menu: 880 881* About Data:: Latent typing, types, values and variables. 882* About Procedures:: The representation and use of procedures. 883* About Expressions:: All kinds of expressions and their meaning. 884* About Closure:: Closure, scoping and environments. 885* Further Reading:: Where to find out more about Scheme. 886 887 888File: guile.info, Node: About Data, Next: About Procedures, Up: Hello Scheme! 889 8903.1 Data Types, Values and Variables 891==================================== 892 893This section discusses the representation of data types and values, what 894it means for Scheme to be a “latently typed” language, and the role of 895variables. We conclude by introducing the Scheme syntaxes for defining 896a new variable, and for changing the value of an existing variable. 897 898* Menu: 899 900* Latent Typing:: Scheme as a "latently typed" language. 901* Values and Variables:: About data types, values and variables. 902* Definition:: Defining variables and setting their values. 903 904 905File: guile.info, Node: Latent Typing, Next: Values and Variables, Up: About Data 906 9073.1.1 Latent Typing 908------------------- 909 910The term “latent typing” is used to describe a computer language, such 911as Scheme, for which you cannot, _in general_, simply look at a 912program’s source code and determine what type of data will be associated 913with a particular variable, or with the result of a particular 914expression. 915 916 Sometimes, of course, you _can_ tell from the code what the type of 917an expression will be. If you have a line in your program that sets the 918variable ‘x’ to the numeric value 1, you can be certain that, 919immediately after that line has executed (and in the absence of multiple 920threads), ‘x’ has the numeric value 1. Or if you write a procedure that 921is designed to concatenate two strings, it is likely that the rest of 922your application will always invoke this procedure with two string 923parameters, and quite probable that the procedure would go wrong in some 924way if it was ever invoked with parameters that were not both strings. 925 926 Nevertheless, the point is that there is nothing in Scheme which 927requires the procedure parameters always to be strings, or ‘x’ always to 928hold a numeric value, and there is no way of declaring in your program 929that such constraints should always be obeyed. In the same vein, there 930is no way to declare the expected type of a procedure’s return value. 931 932 Instead, the types of variables and expressions are only known – in 933general – at run time. If you _need_ to check at some point that a 934value has the expected type, Scheme provides run time procedures that 935you can invoke to do so. But equally, it can be perfectly valid for two 936separate invocations of the same procedure to specify arguments with 937different types, and to return values with different types. 938 939 The next subsection explains what this means in practice, for the 940ways that Scheme programs use data types, values and variables. 941 942 943File: guile.info, Node: Values and Variables, Next: Definition, Prev: Latent Typing, Up: About Data 944 9453.1.2 Values and Variables 946-------------------------- 947 948Scheme provides many data types that you can use to represent your data. 949Primitive types include characters, strings, numbers and procedures. 950Compound types, which allow a group of primitive and compound values to 951be stored together, include lists, pairs, vectors and multi-dimensional 952arrays. In addition, Guile allows applications to define their own data 953types, with the same status as the built-in standard Scheme types. 954 955 As a Scheme program runs, values of all types pop in and out of 956existence. Sometimes values are stored in variables, but more commonly 957they pass seamlessly from being the result of one computation to being 958one of the parameters for the next. 959 960 Consider an example. A string value is created because the 961interpreter reads in a literal string from your program’s source code. 962Then a numeric value is created as the result of calculating the length 963of the string. A second numeric value is created by doubling the 964calculated length. Finally the program creates a list with two elements 965– the doubled length and the original string itself – and stores this 966list in a program variable. 967 968 All of the values involved here – in fact, all values in Scheme – 969carry their type with them. In other words, every value “knows,” at 970runtime, what kind of value it is. A number, a string, a list, 971whatever. 972 973 A variable, on the other hand, has no fixed type. A variable – ‘x’, 974say – is simply the name of a location – a box – in which you can store 975any kind of Scheme value. So the same variable in a program may hold a 976number at one moment, a list of procedures the next, and later a pair of 977strings. The “type” of a variable – insofar as the idea is meaningful 978at all – is simply the type of whatever value the variable happens to be 979storing at a particular moment. 980 981 982File: guile.info, Node: Definition, Prev: Values and Variables, Up: About Data 983 9843.1.3 Defining and Setting Variables 985------------------------------------ 986 987To define a new variable, you use Scheme’s ‘define’ syntax like this: 988 989 (define VARIABLE-NAME VALUE) 990 991 This makes a new variable called VARIABLE-NAME and stores VALUE in it 992as the variable’s initial value. For example: 993 994 ;; Make a variable `x' with initial numeric value 1. 995 (define x 1) 996 997 ;; Make a variable `organization' with an initial string value. 998 (define organization "Free Software Foundation") 999 1000 (In Scheme, a semicolon marks the beginning of a comment that 1001continues until the end of the line. So the lines beginning ‘;;’ are 1002comments.) 1003 1004 Changing the value of an already existing variable is very similar, 1005except that ‘define’ is replaced by the Scheme syntax ‘set!’, like this: 1006 1007 (set! VARIABLE-NAME NEW-VALUE) 1008 1009 Remember that variables do not have fixed types, so NEW-VALUE may 1010have a completely different type from whatever was previously stored in 1011the location named by VARIABLE-NAME. Both of the following examples are 1012therefore correct. 1013 1014 ;; Change the value of `x' to 5. 1015 (set! x 5) 1016 1017 ;; Change the value of `organization' to the FSF's street number. 1018 (set! organization 545) 1019 1020 In these examples, VALUE and NEW-VALUE are literal numeric or string 1021values. In general, however, VALUE and NEW-VALUE can be any Scheme 1022expression. Even though we have not yet covered the forms that Scheme 1023expressions can take (*note About Expressions::), you can probably guess 1024what the following ‘set!’ example does... 1025 1026 (set! x (+ x 1)) 1027 1028 (Note: this is not a complete description of ‘define’ and ‘set!’, 1029because we need to introduce some other aspects of Scheme before the 1030missing pieces can be filled in. If, however, you are already familiar 1031with the structure of Scheme, you may like to read about those missing 1032pieces immediately by jumping ahead to the following references. 1033 1034 • *note Lambda Alternatives::, to read about an alternative form of 1035 the ‘define’ syntax that can be used when defining new procedures. 1036 1037 • *note Procedures with Setters::, to read about an alternative form 1038 of the ‘set!’ syntax that helps with changing a single value in the 1039 depths of a compound data structure.) 1040 1041 • *Note Internal Definitions::, to read about using ‘define’ other 1042 than at top level in a Scheme program, including a discussion of 1043 when it works to use ‘define’ rather than ‘set!’ to change the 1044 value of an existing variable. 1045 1046 1047File: guile.info, Node: About Procedures, Next: About Expressions, Prev: About Data, Up: Hello Scheme! 1048 10493.2 The Representation and Use of Procedures 1050============================================ 1051 1052This section introduces the basics of using and creating Scheme 1053procedures. It discusses the representation of procedures as just 1054another kind of Scheme value, and shows how procedure invocation 1055expressions are constructed. We then explain how ‘lambda’ is used to 1056create new procedures, and conclude by presenting the various shorthand 1057forms of ‘define’ that can be used instead of writing an explicit 1058‘lambda’ expression. 1059 1060* Menu: 1061 1062* Procedures as Values:: Procedures are values like everything else. 1063* Simple Invocation:: How to write a simple procedure invocation. 1064* Creating a Procedure:: How to create your own procedures. 1065* Lambda Alternatives:: Other ways of writing procedure definitions. 1066 1067 1068File: guile.info, Node: Procedures as Values, Next: Simple Invocation, Up: About Procedures 1069 10703.2.1 Procedures as Values 1071-------------------------- 1072 1073One of the great simplifications of Scheme is that a procedure is just 1074another type of value, and that procedure values can be passed around 1075and stored in variables in exactly the same way as, for example, strings 1076and lists. When we talk about a built-in standard Scheme procedure such 1077as ‘open-input-file’, what we actually mean is that there is a 1078pre-defined top level variable called ‘open-input-file’, whose value is 1079a procedure that implements what R5RS says that ‘open-input-file’ should 1080do. 1081 1082 Note that this is quite different from many dialects of Lisp — 1083including Emacs Lisp — in which a program can use the same name with two 1084quite separate meanings: one meaning identifies a Lisp function, while 1085the other meaning identifies a Lisp variable, whose value need have 1086nothing to do with the function that is associated with the first 1087meaning. In these dialects, functions and variables are said to live in 1088different “namespaces”. 1089 1090 In Scheme, on the other hand, all names belong to a single unified 1091namespace, and the variables that these names identify can hold any kind 1092of Scheme value, including procedure values. 1093 1094 One consequence of the “procedures as values” idea is that, if you 1095don’t happen to like the standard name for a Scheme procedure, you can 1096change it. 1097 1098 For example, ‘call-with-current-continuation’ is a very important 1099standard Scheme procedure, but it also has a very long name! So, many 1100programmers use the following definition to assign the same procedure 1101value to the more convenient name ‘call/cc’. 1102 1103 (define call/cc call-with-current-continuation) 1104 1105 Let’s understand exactly how this works. The definition creates a 1106new variable ‘call/cc’, and then sets its value to the value of the 1107variable ‘call-with-current-continuation’; the latter value is a 1108procedure that implements the behaviour that R5RS specifies under the 1109name “call-with-current-continuation”. So ‘call/cc’ ends up holding 1110this value as well. 1111 1112 Now that ‘call/cc’ holds the required procedure value, you could 1113choose to use ‘call-with-current-continuation’ for a completely 1114different purpose, or just change its value so that you will get an 1115error if you accidentally use ‘call-with-current-continuation’ as a 1116procedure in your program rather than ‘call/cc’. For example: 1117 1118 (set! call-with-current-continuation "Not a procedure any more!") 1119 1120 Or you could just leave ‘call-with-current-continuation’ as it was. 1121It’s perfectly fine for more than one variable to hold the same 1122procedure value. 1123 1124 1125File: guile.info, Node: Simple Invocation, Next: Creating a Procedure, Prev: Procedures as Values, Up: About Procedures 1126 11273.2.2 Simple Procedure Invocation 1128--------------------------------- 1129 1130A procedure invocation in Scheme is written like this: 1131 1132 (PROCEDURE [ARG1 [ARG2 ...]]) 1133 1134 In this expression, PROCEDURE can be any Scheme expression whose 1135value is a procedure. Most commonly, however, PROCEDURE is simply the 1136name of a variable whose value is a procedure. 1137 1138 For example, ‘string-append’ is a standard Scheme procedure whose 1139behaviour is to concatenate together all the arguments, which are 1140expected to be strings, that it is given. So the expression 1141 1142 (string-append "/home" "/" "andrew") 1143 1144is a procedure invocation whose result is the string value 1145‘"/home/andrew"’. 1146 1147 Similarly, ‘string-length’ is a standard Scheme procedure that 1148returns the length of a single string argument, so 1149 1150 (string-length "abc") 1151 1152is a procedure invocation whose result is the numeric value 3. 1153 1154 Each of the parameters in a procedure invocation can itself be any 1155Scheme expression. Since a procedure invocation is itself a type of 1156expression, we can put these two examples together to get 1157 1158 (string-length (string-append "/home" "/" "andrew")) 1159 1160— a procedure invocation whose result is the numeric value 12. 1161 1162 (You may be wondering what happens if the two examples are combined 1163the other way round. If we do this, we can make a procedure invocation 1164expression that is _syntactically_ correct: 1165 1166 (string-append "/home" (string-length "abc")) 1167 1168but when this expression is executed, it will cause an error, because 1169the result of ‘(string-length "abc")’ is a numeric value, and 1170‘string-append’ is not designed to accept a numeric value as one of its 1171arguments.) 1172 1173 1174File: guile.info, Node: Creating a Procedure, Next: Lambda Alternatives, Prev: Simple Invocation, Up: About Procedures 1175 11763.2.3 Creating and Using a New Procedure 1177---------------------------------------- 1178 1179Scheme has lots of standard procedures, and Guile provides all of these 1180via predefined top level variables. All of these standard procedures 1181are documented in the later chapters of this reference manual. 1182 1183 Before very long, though, you will want to create new procedures that 1184encapsulate aspects of your own applications’ functionality. To do 1185this, you can use the famous ‘lambda’ syntax. 1186 1187 For example, the value of the following Scheme expression 1188 1189 (lambda (name address) BODY ...) 1190 1191is a newly created procedure that takes two arguments: ‘name’ and 1192‘address’. The behaviour of the new procedure is determined by the 1193sequence of expressions and definitions in the BODY of the procedure 1194definition. (Typically, BODY would use the arguments in some way, or 1195else there wouldn’t be any point in giving them to the procedure.) When 1196invoked, the new procedure returns a value that is the value of the last 1197expression in the BODY. 1198 1199 To make things more concrete, let’s suppose that the two arguments 1200are both strings, and that the purpose of this procedure is to form a 1201combined string that includes these arguments. Then the full lambda 1202expression might look like this: 1203 1204 (lambda (name address) 1205 (string-append "Name=" name ":Address=" address)) 1206 1207 We noted in the previous subsection that the PROCEDURE part of a 1208procedure invocation expression can be any Scheme expression whose value 1209is a procedure. But that’s exactly what a lambda expression is! So we 1210can use a lambda expression directly in a procedure invocation, like 1211this: 1212 1213 ((lambda (name address) 1214 (string-append "Name=" name ":Address=" address)) 1215 "FSF" 1216 "Cambridge") 1217 1218This is a valid procedure invocation expression, and its result is the 1219string: 1220 1221 "Name=FSF:Address=Cambridge" 1222 1223 It is more common, though, to store the procedure value in a variable 1224— 1225 1226 (define make-combined-string 1227 (lambda (name address) 1228 (string-append "Name=" name ":Address=" address))) 1229 1230— and then to use the variable name in the procedure invocation: 1231 1232 (make-combined-string "FSF" "Cambridge") 1233 1234Which has exactly the same result. 1235 1236 It’s important to note that procedures created using ‘lambda’ have 1237exactly the same status as the standard built in Scheme procedures, and 1238can be invoked, passed around, and stored in variables in exactly the 1239same ways. 1240 1241 1242File: guile.info, Node: Lambda Alternatives, Prev: Creating a Procedure, Up: About Procedures 1243 12443.2.4 Lambda Alternatives 1245------------------------- 1246 1247Since it is so common in Scheme programs to want to create a procedure 1248and then store it in a variable, there is an alternative form of the 1249‘define’ syntax that allows you to do just that. 1250 1251 A ‘define’ expression of the form 1252 1253 (define (NAME [ARG1 [ARG2 ...]]) 1254 BODY ...) 1255 1256is exactly equivalent to the longer form 1257 1258 (define NAME 1259 (lambda ([ARG1 [ARG2 ...]]) 1260 BODY ...)) 1261 1262 So, for example, the definition of ‘make-combined-string’ in the 1263previous subsection could equally be written: 1264 1265 (define (make-combined-string name address) 1266 (string-append "Name=" name ":Address=" address)) 1267 1268 This kind of procedure definition creates a procedure that requires 1269exactly the expected number of arguments. There are two further forms 1270of the ‘lambda’ expression, which create a procedure that can accept a 1271variable number of arguments: 1272 1273 (lambda (ARG1 ... . ARGS) BODY ...) 1274 1275 (lambda ARGS BODY ...) 1276 1277The corresponding forms of the alternative ‘define’ syntax are: 1278 1279 (define (NAME ARG1 ... . ARGS) BODY ...) 1280 1281 (define (NAME . ARGS) BODY ...) 1282 1283For details on how these forms work, see *Note Lambda::. 1284 1285 Prior to Guile 2.0, Guile provided an extension to ‘define’ syntax 1286that allowed you to nest the previous extension up to an arbitrary 1287depth. These are no longer provided by default, and instead have been 1288moved to *note Curried Definitions::. 1289 1290 (It could be argued that the alternative ‘define’ forms are rather 1291confusing, especially for newcomers to the Scheme language, as they hide 1292both the role of ‘lambda’ and the fact that procedures are values that 1293are stored in variables in the same way as any other kind of value. On 1294the other hand, they are very convenient, and they are also a good 1295example of another of Scheme’s powerful features: the ability to specify 1296arbitrary syntactic transformations at run time, which can be applied to 1297subsequently read input.) 1298 1299 1300File: guile.info, Node: About Expressions, Next: About Closure, Prev: About Procedures, Up: Hello Scheme! 1301 13023.3 Expressions and Evaluation 1303============================== 1304 1305So far, we have met expressions that _do_ things, such as the ‘define’ 1306expressions that create and initialize new variables, and we have also 1307talked about expressions that have _values_, for example the value of 1308the procedure invocation expression: 1309 1310 (string-append "/home" "/" "andrew") 1311 1312but we haven’t yet been precise about what causes an expression like 1313this procedure invocation to be reduced to its “value”, or how the 1314processing of such expressions relates to the execution of a Scheme 1315program as a whole. 1316 1317 This section clarifies what we mean by an expression’s value, by 1318introducing the idea of “evaluation”. It discusses the side effects 1319that evaluation can have, explains how each of the various types of 1320Scheme expression is evaluated, and describes the behaviour and use of 1321the Guile REPL as a mechanism for exploring evaluation. The section 1322concludes with a very brief summary of Scheme’s common syntactic 1323expressions. 1324 1325* Menu: 1326 1327* Evaluating:: How a Scheme program is executed. 1328* Tail Calls:: Space-safe recursion. 1329* The REPL:: Interacting with the Guile interpreter. 1330* Syntax Summary:: Common syntactic expressions – in brief. 1331 1332 1333File: guile.info, Node: Evaluating, Next: Tail Calls, Up: About Expressions 1334 13353.3.1 Evaluating Expressions and Executing Programs 1336--------------------------------------------------- 1337 1338In Scheme, the process of executing an expression is known as 1339“evaluation”. Evaluation has two kinds of result: 1340 1341 • the “value” of the evaluated expression 1342 1343 • the “side effects” of the evaluation, which consist of any effects 1344 of evaluating the expression that are not represented by the value. 1345 1346 Of the expressions that we have met so far, ‘define’ and ‘set!’ 1347expressions have side effects — the creation or modification of a 1348variable — but no value; ‘lambda’ expressions have values — the newly 1349constructed procedures — but no side effects; and procedure invocation 1350expressions, in general, have either values, or side effects, or both. 1351 1352 It is tempting to try to define more intuitively what we mean by 1353“value” and “side effects”, and what the difference between them is. In 1354general, though, this is extremely difficult. It is also unnecessary; 1355instead, we can quite happily define the behaviour of a Scheme program 1356by specifying how Scheme executes a program as a whole, and then by 1357describing the value and side effects of evaluation for each type of 1358expression individually. 1359 1360So, some(1) definitions... 1361 1362 • A Scheme program consists of a sequence of expressions. 1363 1364 • A Scheme interpreter executes the program by evaluating these 1365 expressions in order, one by one. 1366 1367 • An expression can be 1368 1369 • a piece of literal data, such as a number ‘2.3’ or a string 1370 ‘"Hello world!"’ 1371 • a variable name 1372 • a procedure invocation expression 1373 • one of Scheme’s special syntactic expressions. 1374 1375The following subsections describe how each of these types of expression 1376is evaluated. 1377 1378* Menu: 1379 1380* Eval Literal:: Evaluating literal data. 1381* Eval Variable:: Evaluating variable references. 1382* Eval Procedure:: Evaluating procedure invocation expressions. 1383* Eval Special:: Evaluating special syntactic expressions. 1384 1385 ---------- Footnotes ---------- 1386 1387 (1) These definitions are approximate. For the whole and detailed 1388truth, see *note R5RS syntax: (r5rs)Formal syntax and semantics. 1389 1390 1391File: guile.info, Node: Eval Literal, Next: Eval Variable, Up: Evaluating 1392 13933.3.1.1 Evaluating Literal Data 1394............................... 1395 1396When a literal data expression is evaluated, the value of the expression 1397is simply the value that the expression describes. The evaluation of a 1398literal data expression has no side effects. 1399 1400So, for example, 1401 1402 • the value of the expression ‘"abc"’ is the string value ‘"abc"’ 1403 1404 • the value of the expression ‘3+4i’ is the complex number 3 + 4i 1405 1406 • the value of the expression ‘#(1 2 3)’ is a three-element vector 1407 containing the numeric values 1, 2 and 3. 1408 1409 For any data type which can be expressed literally like this, the 1410syntax of the literal data expression for that data type — in other 1411words, what you need to write in your code to indicate a literal value 1412of that type — is known as the data type’s “read syntax”. This manual 1413specifies the read syntax for each such data type in the section that 1414describes that data type. 1415 1416 Some data types do not have a read syntax. Procedures, for example, 1417cannot be expressed as literal data; they must be created using a 1418‘lambda’ expression (*note Creating a Procedure::) or implicitly using 1419the shorthand form of ‘define’ (*note Lambda Alternatives::). 1420 1421 1422File: guile.info, Node: Eval Variable, Next: Eval Procedure, Prev: Eval Literal, Up: Evaluating 1423 14243.3.1.2 Evaluating a Variable Reference 1425....................................... 1426 1427When an expression that consists simply of a variable name is evaluated, 1428the value of the expression is the value of the named variable. The 1429evaluation of a variable reference expression has no side effects. 1430 1431 So, after 1432 1433 (define key "Paul Evans") 1434 1435the value of the expression ‘key’ is the string value ‘"Paul Evans"’. 1436If KEY is then modified by 1437 1438 (set! key 3.74) 1439 1440the value of the expression ‘key’ is the numeric value 3.74. 1441 1442 If there is no variable with the specified name, evaluation of the 1443variable reference expression signals an error. 1444 1445 1446File: guile.info, Node: Eval Procedure, Next: Eval Special, Prev: Eval Variable, Up: Evaluating 1447 14483.3.1.3 Evaluating a Procedure Invocation Expression 1449.................................................... 1450 1451This is where evaluation starts getting interesting! As already noted, 1452a procedure invocation expression has the form 1453 1454 (PROCEDURE [ARG1 [ARG2 ...]]) 1455 1456where PROCEDURE must be an expression whose value, when evaluated, is a 1457procedure. 1458 1459 The evaluation of a procedure invocation expression like this 1460proceeds by 1461 1462 • evaluating individually the expressions PROCEDURE, ARG1, ARG2, and 1463 so on 1464 1465 • calling the procedure that is the value of the PROCEDURE expression 1466 with the list of values obtained from the evaluations of ARG1, ARG2 1467 etc. as its parameters. 1468 1469 For a procedure defined in Scheme, “calling the procedure with the 1470list of values as its parameters” means binding the values to the 1471procedure’s formal parameters and then evaluating the sequence of 1472expressions that make up the body of the procedure definition. The 1473value of the procedure invocation expression is the value of the last 1474evaluated expression in the procedure body. The side effects of calling 1475the procedure are the combination of the side effects of the sequence of 1476evaluations of expressions in the procedure body. 1477 1478 For a built-in procedure, the value and side-effects of calling the 1479procedure are best described by that procedure’s documentation. 1480 1481 Note that the complete side effects of evaluating a procedure 1482invocation expression consist not only of the side effects of the 1483procedure call, but also of any side effects of the preceding evaluation 1484of the expressions PROCEDURE, ARG1, ARG2, and so on. 1485 1486 To illustrate this, let’s look again at the procedure invocation 1487expression: 1488 1489 (string-length (string-append "/home" "/" "andrew")) 1490 1491 In the outermost expression, PROCEDURE is ‘string-length’ and ARG1 is 1492‘(string-append "/home" "/" "andrew")’. 1493 1494 • Evaluation of ‘string-length’, which is a variable, gives a 1495 procedure value that implements the expected behaviour for 1496 “string-length”. 1497 1498 • Evaluation of ‘(string-append "/home" "/" "andrew")’, which is 1499 another procedure invocation expression, means evaluating each of 1500 1501 • ‘string-append’, which gives a procedure value that implements 1502 the expected behaviour for “string-append” 1503 1504 • ‘"/home"’, which gives the string value ‘"/home"’ 1505 1506 • ‘"/"’, which gives the string value ‘"/"’ 1507 1508 • ‘"andrew"’, which gives the string value ‘"andrew"’ 1509 1510 and then invoking the procedure value with this list of string 1511 values as its arguments. The resulting value is a single string 1512 value that is the concatenation of all the arguments, namely 1513 ‘"/home/andrew"’. 1514 1515 In the evaluation of the outermost expression, the interpreter can 1516now invoke the procedure value obtained from PROCEDURE with the value 1517obtained from ARG1 as its arguments. The resulting value is a numeric 1518value that is the length of the argument string, which is 12. 1519 1520 1521File: guile.info, Node: Eval Special, Prev: Eval Procedure, Up: Evaluating 1522 15233.3.1.4 Evaluating Special Syntactic Expressions 1524................................................ 1525 1526When a procedure invocation expression is evaluated, the procedure and 1527_all_ the argument expressions must be evaluated before the procedure 1528can be invoked. Special syntactic expressions are special because they 1529are able to manipulate their arguments in an unevaluated form, and can 1530choose whether to evaluate any or all of the argument expressions. 1531 1532 Why is this needed? Consider a program fragment that asks the user 1533whether or not to delete a file, and then deletes the file if the user 1534answers yes. 1535 1536 (if (string=? (read-answer "Should I delete this file?") 1537 "yes") 1538 (delete-file file)) 1539 1540 If the outermost ‘(if ...)’ expression here was a procedure 1541invocation expression, the expression ‘(delete-file file)’, whose side 1542effect is to actually delete a file, would already have been evaluated 1543before the ‘if’ procedure even got invoked! Clearly this is no use — 1544the whole point of an ‘if’ expression is that the “consequent” 1545expression is only evaluated if the condition of the ‘if’ expression is 1546“true”. 1547 1548 Therefore ‘if’ must be special syntax, not a procedure. Other 1549special syntaxes that we have already met are ‘define’, ‘set!’ and 1550‘lambda’. ‘define’ and ‘set!’ are syntax because they need to know the 1551variable _name_ that is given as the first argument in a ‘define’ or 1552‘set!’ expression, not that variable’s value. ‘lambda’ is syntax 1553because it does not immediately evaluate the expressions that define the 1554procedure body; instead it creates a procedure object that incorporates 1555these expressions so that they can be evaluated in the future, when that 1556procedure is invoked. 1557 1558 The rules for evaluating each special syntactic expression are 1559specified individually for each special syntax. For a summary of 1560standard special syntax, see *Note Syntax Summary::. 1561 1562 1563File: guile.info, Node: Tail Calls, Next: The REPL, Prev: Evaluating, Up: About Expressions 1564 15653.3.2 Tail calls 1566---------------- 1567 1568Scheme is “properly tail recursive”, meaning that tail calls or 1569recursions from certain contexts do not consume stack space or other 1570resources and can therefore be used on arbitrarily large data or for an 1571arbitrarily long calculation. Consider for example, 1572 1573 (define (foo n) 1574 (display n) 1575 (newline) 1576 (foo (1+ n))) 1577 1578 (foo 1) 1579 ⊣ 1580 1 1581 2 1582 3 1583 ... 1584 1585 ‘foo’ prints numbers infinitely, starting from the given N. It’s 1586implemented by printing N then recursing to itself to print N+1 and so 1587on. This recursion is a tail call, it’s the last thing done, and in 1588Scheme such tail calls can be made without limit. 1589 1590 Or consider a case where a value is returned, a version of the SRFI-1 1591‘last’ function (*note SRFI-1 Selectors::) returning the last element of 1592a list, 1593 1594 (define (my-last lst) 1595 (if (null? (cdr lst)) 1596 (car lst) 1597 (my-last (cdr lst)))) 1598 1599 (my-last '(1 2 3)) ⇒ 3 1600 1601 If the list has more than one element, ‘my-last’ applies itself to 1602the ‘cdr’. This recursion is a tail call, there’s no code after it, and 1603the return value is the return value from that call. In Scheme this can 1604be used on an arbitrarily long list argument. 1605 1606 1607 A proper tail call is only available from certain contexts, namely 1608the following special form positions, 1609 1610 • ‘and’ — last expression 1611 1612 • ‘begin’ — last expression 1613 1614 • ‘case’ — last expression in each clause 1615 1616 • ‘cond’ — last expression in each clause, and the call to a ‘=>’ 1617 procedure is a tail call 1618 1619 • ‘do’ — last result expression 1620 1621 • ‘if’ — “true” and “false” leg expressions 1622 1623 • ‘lambda’ — last expression in body 1624 1625 • ‘let’, ‘let*’, ‘letrec’, ‘let-syntax’, ‘letrec-syntax’ — last 1626 expression in body 1627 1628 • ‘or’ — last expression 1629 1630The following core functions make tail calls, 1631 1632 • ‘apply’ — tail call to given procedure 1633 1634 • ‘call-with-current-continuation’ — tail call to the procedure 1635 receiving the new continuation 1636 1637 • ‘call-with-values’ — tail call to the values-receiving procedure 1638 1639 • ‘eval’ — tail call to evaluate the form 1640 1641 • ‘string-any’, ‘string-every’ — tail call to predicate on the last 1642 character (if that point is reached) 1643 1644 1645 The above are just core functions and special forms. Tail calls in 1646other modules are described with the relevant documentation, for example 1647SRFI-1 ‘any’ and ‘every’ (*note SRFI-1 Searching::). 1648 1649 It will be noted there are a lot of places which could potentially be 1650tail calls, for instance the last call in a ‘for-each’, but only those 1651explicitly described are guaranteed. 1652 1653 1654File: guile.info, Node: The REPL, Next: Syntax Summary, Prev: Tail Calls, Up: About Expressions 1655 16563.3.3 Using the Guile REPL 1657-------------------------- 1658 1659If you start Guile without specifying a particular program for it to 1660execute, Guile enters its standard Read Evaluate Print Loop — or “REPL” 1661for short. In this mode, Guile repeatedly reads in the next Scheme 1662expression that the user types, evaluates it, and prints the resulting 1663value. 1664 1665 The REPL is a useful mechanism for exploring the evaluation behaviour 1666described in the previous subsection. If you type ‘string-append’, for 1667example, the REPL replies ‘#<primitive-procedure string-append>’, 1668illustrating the relationship between the variable ‘string-append’ and 1669the procedure value stored in that variable. 1670 1671 In this manual, the notation ⇒ is used to mean “evaluates to”. 1672Wherever you see an example of the form 1673 1674 EXPRESSION 1675 ⇒ 1676 RESULT 1677 1678feel free to try it out yourself by typing EXPRESSION into the REPL and 1679checking that it gives the expected RESULT. 1680 1681 1682File: guile.info, Node: Syntax Summary, Prev: The REPL, Up: About Expressions 1683 16843.3.4 Summary of Common Syntax 1685------------------------------ 1686 1687This subsection lists the most commonly used Scheme syntactic 1688expressions, simply so that you will recognize common special syntax 1689when you see it. For a full description of each of these syntaxes, 1690follow the appropriate reference. 1691 1692 ‘lambda’ (*note Lambda::) is used to construct procedure objects. 1693 1694 ‘define’ (*note Top Level::) is used to create a new variable and set 1695its initial value. 1696 1697 ‘set!’ (*note Top Level::) is used to modify an existing variable’s 1698value. 1699 1700 ‘let’, ‘let*’ and ‘letrec’ (*note Local Bindings::) create an inner 1701lexical environment for the evaluation of a sequence of expressions, in 1702which a specified set of local variables is bound to the values of a 1703corresponding set of expressions. For an introduction to environments, 1704see *Note About Closure::. 1705 1706 ‘begin’ (*note begin::) executes a sequence of expressions in order 1707and returns the value of the last expression. Note that this is not the 1708same as a procedure which returns its last argument, because the 1709evaluation of a procedure invocation expression does not guarantee to 1710evaluate the arguments in order. 1711 1712 ‘if’ and ‘cond’ (*note Conditionals::) provide conditional evaluation 1713of argument expressions depending on whether one or more conditions 1714evaluate to “true” or “false”. 1715 1716 ‘case’ (*note Conditionals::) provides conditional evaluation of 1717argument expressions depending on whether a variable has one of a 1718specified group of values. 1719 1720 ‘and’ (*note and or::) executes a sequence of expressions in order 1721until either there are no expressions left, or one of them evaluates to 1722“false”. 1723 1724 ‘or’ (*note and or::) executes a sequence of expressions in order 1725until either there are no expressions left, or one of them evaluates to 1726“true”. 1727 1728 1729File: guile.info, Node: About Closure, Next: Further Reading, Prev: About Expressions, Up: Hello Scheme! 1730 17313.4 The Concept of Closure 1732========================== 1733 1734The concept of “closure” is the idea that a lambda expression “captures” 1735the variable bindings that are in lexical scope at the point where the 1736lambda expression occurs. The procedure created by the lambda 1737expression can refer to and mutate the captured bindings, and the values 1738of those bindings persist between procedure calls. 1739 1740 This section explains and explores the various parts of this idea in 1741more detail. 1742 1743* Menu: 1744 1745* About Environments:: Names, locations, values and environments. 1746* Local Variables:: Local variables and local environments. 1747* Chaining:: Environment chaining. 1748* Lexical Scope:: The meaning of lexical scoping. 1749* Closure:: Explaining the concept of closure. 1750* Serial Number:: Example 1: a serial number generator. 1751* Shared Variable:: Example 2: a shared persistent variable. 1752* Callback Closure:: Example 3: the callback closure problem. 1753* OO Closure:: Example 4: object orientation. 1754 1755 1756File: guile.info, Node: About Environments, Next: Local Variables, Up: About Closure 1757 17583.4.1 Names, Locations, Values and Environments 1759----------------------------------------------- 1760 1761We said earlier that a variable name in a Scheme program is associated 1762with a location in which any kind of Scheme value may be stored. 1763(Incidentally, the term “vcell” is often used in Lisp and Scheme circles 1764as an alternative to “location”.) Thus part of what we mean when we 1765talk about “creating a variable” is in fact establishing an association 1766between a name, or identifier, that is used by the Scheme program code, 1767and the variable location to which that name refers. Although the value 1768that is stored in that location may change, the location to which a 1769given name refers is always the same. 1770 1771 We can illustrate this by breaking down the operation of the ‘define’ 1772syntax into three parts: ‘define’ 1773 1774 • creates a new location 1775 1776 • establishes an association between that location and the name 1777 specified as the first argument of the ‘define’ expression 1778 1779 • stores in that location the value obtained by evaluating the second 1780 argument of the ‘define’ expression. 1781 1782 A collection of associations between names and locations is called an 1783“environment”. When you create a top level variable in a program using 1784‘define’, the name-location association for that variable is added to 1785the “top level” environment. The “top level” environment also includes 1786name-location associations for all the procedures that are supplied by 1787standard Scheme. 1788 1789 It is also possible to create environments other than the top level 1790one, and to create variable bindings, or name-location associations, in 1791those environments. This ability is a key ingredient in the concept of 1792closure; the next subsection shows how it is done. 1793 1794 1795File: guile.info, Node: Local Variables, Next: Chaining, Prev: About Environments, Up: About Closure 1796 17973.4.2 Local Variables and Environments 1798-------------------------------------- 1799 1800We have seen how to create top level variables using the ‘define’ syntax 1801(*note Definition::). It is often useful to create variables that are 1802more limited in their scope, typically as part of a procedure body. In 1803Scheme, this is done using the ‘let’ syntax, or one of its modified 1804forms ‘let*’ and ‘letrec’. These syntaxes are described in full later 1805in the manual (*note Local Bindings::). Here our purpose is to 1806illustrate their use just enough that we can see how local variables 1807work. 1808 1809 For example, the following code uses a local variable ‘s’ to simplify 1810the computation of the area of a triangle given the lengths of its three 1811sides. 1812 1813 (define a 5.3) 1814 (define b 4.7) 1815 (define c 2.8) 1816 1817 (define area 1818 (let ((s (/ (+ a b c) 2))) 1819 (sqrt (* s (- s a) (- s b) (- s c))))) 1820 1821 The effect of the ‘let’ expression is to create a new environment 1822and, within this environment, an association between the name ‘s’ and a 1823new location whose initial value is obtained by evaluating ‘(/ (+ a b c) 18242)’. The expressions in the body of the ‘let’, namely ‘(sqrt (* s (- s 1825a) (- s b) (- s c)))’, are then evaluated in the context of the new 1826environment, and the value of the last expression evaluated becomes the 1827value of the whole ‘let’ expression, and therefore the value of the 1828variable ‘area’. 1829 1830 1831File: guile.info, Node: Chaining, Next: Lexical Scope, Prev: Local Variables, Up: About Closure 1832 18333.4.3 Environment Chaining 1834-------------------------- 1835 1836In the example of the previous subsection, we glossed over an important 1837point. The body of the ‘let’ expression in that example refers not only 1838to the local variable ‘s’, but also to the top level variables ‘a’, ‘b’, 1839‘c’ and ‘sqrt’. (‘sqrt’ is the standard Scheme procedure for 1840calculating a square root.) If the body of the ‘let’ expression is 1841evaluated in the context of the _local_ ‘let’ environment, how does the 1842evaluation get at the values of these top level variables? 1843 1844 The answer is that the local environment created by a ‘let’ 1845expression automatically has a reference to its containing environment — 1846in this case the top level environment — and that the Scheme interpreter 1847automatically looks for a variable binding in the containing environment 1848if it doesn’t find one in the local environment. More generally, every 1849environment except for the top level one has a reference to its 1850containing environment, and the interpreter keeps searching back up the 1851chain of environments — from most local to top level — until it either 1852finds a variable binding for the required identifier or exhausts the 1853chain. 1854 1855 This description also determines what happens when there is more than 1856one variable binding with the same name. Suppose, continuing the 1857example of the previous subsection, that there was also a pre-existing 1858top level variable ‘s’ created by the expression: 1859 1860 (define s "Some beans, my lord!") 1861 1862 Then both the top level environment and the local ‘let’ environment 1863would contain bindings for the name ‘s’. When evaluating code within 1864the ‘let’ body, the interpreter looks first in the local ‘let’ 1865environment, and so finds the binding for ‘s’ created by the ‘let’ 1866syntax. Even though this environment has a reference to the top level 1867environment, which also has a binding for ‘s’, the interpreter doesn’t 1868get as far as looking there. When evaluating code outside the ‘let’ 1869body, the interpreter looks up variable names in the top level 1870environment, so the name ‘s’ refers to the top level variable. 1871 1872 Within the ‘let’ body, the binding for ‘s’ in the local environment 1873is said to “shadow” the binding for ‘s’ in the top level environment. 1874 1875 1876File: guile.info, Node: Lexical Scope, Next: Closure, Prev: Chaining, Up: About Closure 1877 18783.4.4 Lexical Scope 1879------------------- 1880 1881The rules that we have just been describing are the details of how 1882Scheme implements “lexical scoping”. This subsection takes a brief 1883diversion to explain what lexical scope means in general and to present 1884an example of non-lexical scoping. 1885 1886 “Lexical scope” in general is the idea that 1887 1888 • an identifier at a particular place in a program always refers to 1889 the same variable location — where “always” means “every time that 1890 the containing expression is executed”, and that 1891 1892 • the variable location to which it refers can be determined by 1893 static examination of the source code context in which that 1894 identifier appears, without having to consider the flow of 1895 execution through the program as a whole. 1896 1897 In practice, lexical scoping is the norm for most programming 1898languages, and probably corresponds to what you would intuitively 1899consider to be “normal”. You may even be wondering how the situation 1900could possibly — and usefully — be otherwise. To demonstrate that 1901another kind of scoping is possible, therefore, and to compare it 1902against lexical scoping, the following subsection presents an example of 1903non-lexical scoping and examines in detail how its behavior differs from 1904the corresponding lexically scoped code. 1905 1906* Menu: 1907 1908* Scoping Example:: An example of non-lexical scoping. 1909 1910 1911File: guile.info, Node: Scoping Example, Up: Lexical Scope 1912 19133.4.4.1 An Example of Non-Lexical Scoping 1914......................................... 1915 1916To demonstrate that non-lexical scoping does exist and can be useful, we 1917present the following example from Emacs Lisp, which is a “dynamically 1918scoped” language. 1919 1920 (defvar currency-abbreviation "USD") 1921 1922 (defun currency-string (units hundredths) 1923 (concat currency-abbreviation 1924 (number-to-string units) 1925 "." 1926 (number-to-string hundredths))) 1927 1928 (defun french-currency-string (units hundredths) 1929 (let ((currency-abbreviation "FRF")) 1930 (currency-string units hundredths))) 1931 1932 The question to focus on here is: what does the identifier 1933‘currency-abbreviation’ refer to in the ‘currency-string’ function? The 1934answer, in Emacs Lisp, is that all variable bindings go onto a single 1935stack, and that ‘currency-abbreviation’ refers to the topmost binding 1936from that stack which has the name “currency-abbreviation”. The binding 1937that is created by the ‘defvar’ form, to the value ‘"USD"’, is only 1938relevant if none of the code that calls ‘currency-string’ rebinds the 1939name “currency-abbreviation” in the meanwhile. 1940 1941 The second function ‘french-currency-string’ works precisely by 1942taking advantage of this behaviour. It creates a new binding for the 1943name “currency-abbreviation” which overrides the one established by the 1944‘defvar’ form. 1945 1946 ;; Note! This is Emacs Lisp evaluation, not Scheme! 1947 (french-currency-string 33 44) 1948 ⇒ 1949 "FRF33.44" 1950 1951 Now let’s look at the corresponding, _lexically scoped_ Scheme code: 1952 1953 (define currency-abbreviation "USD") 1954 1955 (define (currency-string units hundredths) 1956 (string-append currency-abbreviation 1957 (number->string units) 1958 "." 1959 (number->string hundredths))) 1960 1961 (define (french-currency-string units hundredths) 1962 (let ((currency-abbreviation "FRF")) 1963 (currency-string units hundredths))) 1964 1965 According to the rules of lexical scoping, the 1966‘currency-abbreviation’ in ‘currency-string’ refers to the variable 1967location in the innermost environment at that point in the code which 1968has a binding for ‘currency-abbreviation’, which is the variable 1969location in the top level environment created by the preceding ‘(define 1970currency-abbreviation ...)’ expression. 1971 1972 In Scheme, therefore, the ‘french-currency-string’ procedure does not 1973work as intended. The variable binding that it creates for 1974“currency-abbreviation” is purely local to the code that forms the body 1975of the ‘let’ expression. Since this code doesn’t directly use the name 1976“currency-abbreviation” at all, the binding is pointless. 1977 1978 (french-currency-string 33 44) 1979 ⇒ 1980 "USD33.44" 1981 1982 This begs the question of how the Emacs Lisp behaviour can be 1983implemented in Scheme. In general, this is a design question whose 1984answer depends upon the problem that is being addressed. In this case, 1985the best answer may be that ‘currency-string’ should be redesigned so 1986that it can take an optional third argument. This third argument, if 1987supplied, is interpreted as a currency abbreviation that overrides the 1988default. 1989 1990 It is possible to change ‘french-currency-string’ so that it mostly 1991works without changing ‘currency-string’, but the fix is inelegant, and 1992susceptible to interrupts that could leave the ‘currency-abbreviation’ 1993variable in the wrong state: 1994 1995 (define (french-currency-string units hundredths) 1996 (set! currency-abbreviation "FRF") 1997 (let ((result (currency-string units hundredths))) 1998 (set! currency-abbreviation "USD") 1999 result)) 2000 2001 The key point here is that the code does not create any local binding 2002for the identifier ‘currency-abbreviation’, so all occurrences of this 2003identifier refer to the top level variable. 2004 2005 2006File: guile.info, Node: Closure, Next: Serial Number, Prev: Lexical Scope, Up: About Closure 2007 20083.4.5 Closure 2009------------- 2010 2011Consider a ‘let’ expression that doesn’t contain any ‘lambda’s: 2012 2013 (let ((s (/ (+ a b c) 2))) 2014 (sqrt (* s (- s a) (- s b) (- s c)))) 2015 2016When the Scheme interpreter evaluates this, it 2017 2018 • creates a new environment with a reference to the environment that 2019 was current when it encountered the ‘let’ 2020 2021 • creates a variable binding for ‘s’ in the new environment, with 2022 value given by ‘(/ (+ a b c) 2)’ 2023 2024 • evaluates the expression in the body of the ‘let’ in the context of 2025 the new local environment, and remembers the value ‘V’ 2026 2027 • forgets the local environment 2028 2029 • continues evaluating the expression that contained the ‘let’, using 2030 the value ‘V’ as the value of the ‘let’ expression, in the context 2031 of the containing environment. 2032 2033 After the ‘let’ expression has been evaluated, the local environment 2034that was created is simply forgotten, and there is no longer any way to 2035access the binding that was created in this environment. If the same 2036code is evaluated again, it will follow the same steps again, creating a 2037second new local environment that has no connection with the first, and 2038then forgetting this one as well. 2039 2040 If the ‘let’ body contains a ‘lambda’ expression, however, the local 2041environment is _not_ forgotten. Instead, it becomes associated with the 2042procedure that is created by the ‘lambda’ expression, and is reinstated 2043every time that that procedure is called. In detail, this works as 2044follows. 2045 2046 • When the Scheme interpreter evaluates a ‘lambda’ expression, to 2047 create a procedure object, it stores the current environment as 2048 part of the procedure definition. 2049 2050 • Then, whenever that procedure is called, the interpreter reinstates 2051 the environment that is stored in the procedure definition and 2052 evaluates the procedure body within the context of that 2053 environment. 2054 2055 The result is that the procedure body is always evaluated in the 2056context of the environment that was current when the procedure was 2057created. 2058 2059 This is what is meant by “closure”. The next few subsections present 2060examples that explore the usefulness of this concept. 2061 2062 2063File: guile.info, Node: Serial Number, Next: Shared Variable, Prev: Closure, Up: About Closure 2064 20653.4.6 Example 1: A Serial Number Generator 2066------------------------------------------ 2067 2068This example uses closure to create a procedure with a variable binding 2069that is private to the procedure, like a local variable, but whose value 2070persists between procedure calls. 2071 2072 (define (make-serial-number-generator) 2073 (let ((current-serial-number 0)) 2074 (lambda () 2075 (set! current-serial-number (+ current-serial-number 1)) 2076 current-serial-number))) 2077 2078 (define entry-sn-generator (make-serial-number-generator)) 2079 2080 (entry-sn-generator) 2081 ⇒ 2082 1 2083 2084 (entry-sn-generator) 2085 ⇒ 2086 2 2087 2088 When ‘make-serial-number-generator’ is called, it creates a local 2089environment with a binding for ‘current-serial-number’ whose initial 2090value is 0, then, within this environment, creates a procedure. The 2091local environment is stored within the created procedure object and so 2092persists for the lifetime of the created procedure. 2093 2094 Every time the created procedure is invoked, it increments the value 2095of the ‘current-serial-number’ binding in the captured environment and 2096then returns the current value. 2097 2098 Note that ‘make-serial-number-generator’ can be called again to 2099create a second serial number generator that is independent of the 2100first. Every new invocation of ‘make-serial-number-generator’ creates a 2101new local ‘let’ environment and returns a new procedure object with an 2102association to this environment. 2103 2104 2105File: guile.info, Node: Shared Variable, Next: Callback Closure, Prev: Serial Number, Up: About Closure 2106 21073.4.7 Example 2: A Shared Persistent Variable 2108--------------------------------------------- 2109 2110This example uses closure to create two procedures, ‘get-balance’ and 2111‘deposit’, that both refer to the same captured local environment so 2112that they can both access the ‘balance’ variable binding inside that 2113environment. The value of this variable binding persists between calls 2114to either procedure. 2115 2116 Note that the captured ‘balance’ variable binding is private to these 2117two procedures: it is not directly accessible to any other code. It can 2118only be accessed indirectly via ‘get-balance’ or ‘deposit’, as 2119illustrated by the ‘withdraw’ procedure. 2120 2121 (define get-balance #f) 2122 (define deposit #f) 2123 2124 (let ((balance 0)) 2125 (set! get-balance 2126 (lambda () 2127 balance)) 2128 (set! deposit 2129 (lambda (amount) 2130 (set! balance (+ balance amount)) 2131 balance))) 2132 2133 (define (withdraw amount) 2134 (deposit (- amount))) 2135 2136 (get-balance) 2137 ⇒ 2138 0 2139 2140 (deposit 50) 2141 ⇒ 2142 50 2143 2144 (withdraw 75) 2145 ⇒ 2146 -25 2147 2148 An important detail here is that the ‘get-balance’ and ‘deposit’ 2149variables must be set up by ‘define’ing them at top level and then 2150‘set!’ing their values inside the ‘let’ body. Using ‘define’ within the 2151‘let’ body would not work: this would create variable bindings within 2152the local ‘let’ environment that would not be accessible at top level. 2153 2154 2155File: guile.info, Node: Callback Closure, Next: OO Closure, Prev: Shared Variable, Up: About Closure 2156 21573.4.8 Example 3: The Callback Closure Problem 2158--------------------------------------------- 2159 2160A frequently used programming model for library code is to allow an 2161application to register a callback function for the library to call when 2162some particular event occurs. It is often useful for the application to 2163make several such registrations using the same callback function, for 2164example if several similar library events can be handled using the same 2165application code, but the need then arises to distinguish the callback 2166function calls that are associated with one callback registration from 2167those that are associated with different callback registrations. 2168 2169 In languages without the ability to create functions dynamically, 2170this problem is usually solved by passing a ‘user_data’ parameter on the 2171registration call, and including the value of this parameter as one of 2172the parameters on the callback function. Here is an example of 2173declarations using this solution in C: 2174 2175 typedef void (event_handler_t) (int event_type, 2176 void *user_data); 2177 2178 void register_callback (int event_type, 2179 event_handler_t *handler, 2180 void *user_data); 2181 2182 In Scheme, closure can be used to achieve the same functionality 2183without requiring the library code to store a ‘user-data’ for each 2184callback registration. 2185 2186 ;; In the library: 2187 2188 (define (register-callback event-type handler-proc) 2189 ...) 2190 2191 ;; In the application: 2192 2193 (define (make-handler event-type user-data) 2194 (lambda () 2195 ... 2196 <code referencing event-type and user-data> 2197 ...)) 2198 2199 (register-callback event-type 2200 (make-handler event-type ...)) 2201 2202 As far as the library is concerned, ‘handler-proc’ is a procedure 2203with no arguments, and all the library has to do is call it when the 2204appropriate event occurs. From the application’s point of view, though, 2205the handler procedure has used closure to capture an environment that 2206includes all the context that the handler code needs — ‘event-type’ and 2207‘user-data’ — to handle the event correctly. 2208 2209 2210File: guile.info, Node: OO Closure, Prev: Callback Closure, Up: About Closure 2211 22123.4.9 Example 4: Object Orientation 2213----------------------------------- 2214 2215Closure is the capture of an environment, containing persistent variable 2216bindings, within the definition of a procedure or a set of related 2217procedures. This is rather similar to the idea in some object oriented 2218languages of encapsulating a set of related data variables inside an 2219“object”, together with a set of “methods” that operate on the 2220encapsulated data. The following example shows how closure can be used 2221to emulate the ideas of objects, methods and encapsulation in Scheme. 2222 2223 (define (make-account) 2224 (let ((balance 0)) 2225 (define (get-balance) 2226 balance) 2227 (define (deposit amount) 2228 (set! balance (+ balance amount)) 2229 balance) 2230 (define (withdraw amount) 2231 (deposit (- amount))) 2232 2233 (lambda args 2234 (apply 2235 (case (car args) 2236 ((get-balance) get-balance) 2237 ((deposit) deposit) 2238 ((withdraw) withdraw) 2239 (else (error "Invalid method!"))) 2240 (cdr args))))) 2241 2242 Each call to ‘make-account’ creates and returns a new procedure, 2243created by the expression in the example code that begins “(lambda 2244args”. 2245 2246 (define my-account (make-account)) 2247 2248 my-account 2249 ⇒ 2250 #<procedure args> 2251 2252 This procedure acts as an account object with methods ‘get-balance’, 2253‘deposit’ and ‘withdraw’. To apply one of the methods to the account, 2254you call the procedure with a symbol indicating the required method as 2255the first parameter, followed by any other parameters that are required 2256by that method. 2257 2258 (my-account 'get-balance) 2259 ⇒ 2260 0 2261 2262 (my-account 'withdraw 5) 2263 ⇒ 2264 -5 2265 2266 (my-account 'deposit 396) 2267 ⇒ 2268 391 2269 2270 (my-account 'get-balance) 2271 ⇒ 2272 391 2273 2274 Note how, in this example, both the current balance and the helper 2275procedures ‘get-balance’, ‘deposit’ and ‘withdraw’, used to implement 2276the guts of the account object’s methods, are all stored in variable 2277bindings within the private local environment captured by the ‘lambda’ 2278expression that creates the account object procedure. 2279 2280 2281File: guile.info, Node: Further Reading, Prev: About Closure, Up: Hello Scheme! 2282 22833.5 Further Reading 2284=================== 2285 2286 • The website <http://www.schemers.org/> is a good starting point for 2287 all things Scheme. 2288 2289 • Dorai Sitaram’s online Scheme tutorial, “Teach Yourself Scheme in 2290 Fixnum Days”, at 2291 <http://www.ccs.neu.edu/home/dorai/t-y-scheme/t-y-scheme.html>. 2292 Includes a nice explanation of continuations. 2293 2294 • The complete text of “Structure and Interpretation of Computer 2295 Programs”, the classic introduction to computer science and Scheme 2296 by Hal Abelson, Jerry Sussman and Julie Sussman, is now available 2297 online at <http://mitpress.mit.edu/sicp/sicp.html>. This site also 2298 provides teaching materials related to the book, and all the source 2299 code used in the book, in a form suitable for loading and running. 2300 2301 2302File: guile.info, Node: Programming in Scheme, Next: Programming in C, Prev: Hello Scheme!, Up: Top 2303 23044 Programming in Scheme 2305*********************** 2306 2307Guile’s core language is Scheme, and a lot can be achieved simply by 2308using Guile to write and run Scheme programs — as opposed to having to 2309dive into C code. In this part of the manual, we explain how to use 2310Guile in this mode, and describe the tools that Guile provides to help 2311you with script writing, debugging, and packaging your programs for 2312distribution. 2313 2314 For detailed reference information on the variables, functions, and 2315so on that make up Guile’s application programming interface (API), see 2316*note API Reference::. 2317 2318* Menu: 2319 2320* Guile Scheme:: Guile’s implementation of Scheme. 2321* Invoking Guile:: Selecting optional features when starting Guile. 2322* Guile Scripting:: How to write Guile scripts. 2323* Using Guile Interactively:: Guile’s REPL features. 2324* Using Guile in Emacs:: Guile and Emacs. 2325* Using Guile Tools:: A guild of scheming wizards. 2326* Installing Site Packages:: Installing Scheme code. 2327* Distributing Guile Code:: Building and distributing your code. 2328 2329 2330File: guile.info, Node: Guile Scheme, Next: Invoking Guile, Up: Programming in Scheme 2331 23324.1 Guile’s Implementation of Scheme 2333==================================== 2334 2335Guile’s core language is Scheme, which is specified and described in the 2336series of reports known as “RnRS”. “RnRS” is shorthand for the 2337“Revised^n Report on the Algorithmic Language Scheme”. Guile complies 2338fully with R5RS (*note Introduction: (r5rs)Top.), and is largely 2339compliant with R6RS and R7RS. 2340 2341 Guile also has many extensions that go beyond these reports. Some of 2342the areas where Guile extends standard Scheme are: 2343 2344 • Guile’s interactive documentation system 2345 2346 • Guile’s support for POSIX-compliant network programming 2347 2348 • GOOPS – Guile’s framework for object oriented programming. 2349 2350 2351File: guile.info, Node: Invoking Guile, Next: Guile Scripting, Prev: Guile Scheme, Up: Programming in Scheme 2352 23534.2 Invoking Guile 2354================== 2355 2356Many features of Guile depend on and can be changed by information that 2357the user provides either before or when Guile is started. Below is a 2358description of what information to provide and how to provide it. 2359 2360* Menu: 2361 2362* Command-line Options:: Command-line options understood by Guile. 2363* Environment Variables:: Variables that affect Guile’s behavior. 2364 2365 2366File: guile.info, Node: Command-line Options, Next: Environment Variables, Up: Invoking Guile 2367 23684.2.1 Command-line Options 2369-------------------------- 2370 2371Here we describe Guile’s command-line processing in detail. Guile 2372processes its arguments from left to right, recognizing the switches 2373described below. For examples, see *note Scripting Examples::. 2374 2375‘SCRIPT ARG...’ 2376‘-s SCRIPT ARG...’ 2377 By default, Guile will read a file named on the command line as a 2378 script. Any command-line arguments ARG... following SCRIPT become 2379 the script’s arguments; the ‘command-line’ function returns a list 2380 of strings of the form ‘(SCRIPT ARG...)’. 2381 2382 It is possible to name a file using a leading hyphen, for example, 2383 ‘-myfile.scm’. In this case, the file name must be preceded by 2384 ‘-s’ to tell Guile that a (script) file is being named. 2385 2386 Scripts are read and evaluated as Scheme source code just as the 2387 ‘load’ function would. After loading SCRIPT, Guile exits. 2388 2389‘-c EXPR ARG...’ 2390 Evaluate EXPR as Scheme code, and then exit. Any command-line 2391 arguments ARG... following EXPR become command-line arguments; the 2392 ‘command-line’ function returns a list of strings of the form 2393 ‘(GUILE ARG...)’, where GUILE is the path of the Guile executable. 2394 2395‘-- ARG...’ 2396 Run interactively, prompting the user for expressions and 2397 evaluating them. Any command-line arguments ARG... following the 2398 ‘--’ become command-line arguments for the interactive session; the 2399 ‘command-line’ function returns a list of strings of the form 2400 ‘(GUILE ARG...)’, where GUILE is the path of the Guile executable. 2401 2402‘-L DIRECTORY’ 2403 Add DIRECTORY to the front of Guile’s module load path. The given 2404 directories are searched in the order given on the command line and 2405 before any directories in the ‘GUILE_LOAD_PATH’ environment 2406 variable. Paths added here are _not_ in effect during execution of 2407 the user’s ‘.guile’ file. 2408 2409‘-C DIRECTORY’ 2410 Like ‘-L’, but adjusts the load path for _compiled_ files. 2411 2412‘-x EXTENSION’ 2413 Add EXTENSION to the front of Guile’s load extension list (*note 2414 ‘%load-extensions’: Load Paths.). The specified extensions are 2415 tried in the order given on the command line, and before the 2416 default load extensions. Extensions added here are _not_ in effect 2417 during execution of the user’s ‘.guile’ file. 2418 2419‘-l FILE’ 2420 Load Scheme source code from FILE, and continue processing the 2421 command line. 2422 2423‘-e FUNCTION’ 2424 Make FUNCTION the “entry point” of the script. After loading the 2425 script file (with ‘-s’) or evaluating the expression (with ‘-c’), 2426 apply FUNCTION to a list containing the program name and the 2427 command-line arguments—the list provided by the ‘command-line’ 2428 function. 2429 2430 A ‘-e’ switch can appear anywhere in the argument list, but Guile 2431 always invokes the FUNCTION as the _last_ action it performs. This 2432 is weird, but because of the way script invocation works under 2433 POSIX, the ‘-s’ option must always come last in the list. 2434 2435 The FUNCTION is most often a simple symbol that names a function 2436 that is defined in the script. It can also be of the form ‘(@ 2437 MODULE-NAME SYMBOL)’, and in that case, the symbol is looked up in 2438 the module named MODULE-NAME. 2439 2440 As a shorthand you can use the form ‘(symbol ...)’, that is, a list 2441 of only symbols that doesn’t start with ‘@’. It is equivalent to 2442 ‘(@ MODULE-NAME main)’, where MODULE-NAME is ‘(symbol ...)’ form. 2443 *Note Using Guile Modules:: and *note Scripting Examples::. 2444 2445‘-ds’ 2446 Treat a final ‘-s’ option as if it occurred at this point in the 2447 command line; load the script here. 2448 2449 This switch is necessary because, although the POSIX script 2450 invocation mechanism effectively requires the ‘-s’ option to appear 2451 last, the programmer may well want to run the script before other 2452 actions requested on the command line. For examples, see *note 2453 Scripting Examples::. 2454 2455‘\’ 2456 Read more command-line arguments, starting from the second line of 2457 the script file. *Note The Meta Switch::. 2458 2459‘--use-srfi=LIST’ 2460 The option ‘--use-srfi’ expects a comma-separated list of numbers, 2461 each representing a SRFI module to be loaded into the interpreter 2462 before evaluating a script file or starting the REPL. Additionally, 2463 the feature identifier for the loaded SRFIs is recognized by the 2464 procedure ‘cond-expand’ when this option is used. 2465 2466 Here is an example that loads the modules SRFI-8 (’receive’) and 2467 SRFI-13 (’string library’) before the GUILE interpreter is started: 2468 2469 guile --use-srfi=8,13 2470 2471‘--r6rs’ 2472 Adapt Guile’s initial environment to better support R6RS. *Note 2473 R6RS Incompatibilities::, for some caveats. 2474 2475‘--r7rs’ 2476 Adapt Guile’s initial environment to better support R7RS. *Note 2477 R7RS Incompatibilities::, for some caveats. 2478 2479‘--debug’ 2480 Start with the debugging virtual machine (VM) engine. Using the 2481 debugging VM will enable support for VM hooks, which are needed for 2482 tracing, breakpoints, and accurate call counts when profiling. The 2483 debugging VM is slower than the regular VM, though, by about ten 2484 percent. *Note VM Hooks::, for more information. 2485 2486 By default, the debugging VM engine is only used when entering an 2487 interactive session. When executing a script with ‘-s’ or ‘-c’, 2488 the normal, faster VM is used by default. 2489 2490‘--no-debug’ 2491 Do not use the debugging VM engine, even when entering an 2492 interactive session. 2493 2494 Note that, despite the name, Guile running with ‘--no-debug’ _does_ 2495 support the usual debugging facilities, such as printing a detailed 2496 backtrace upon error. The only difference with ‘--debug’ is lack 2497 of support for VM hooks and the facilities that build upon it (see 2498 above). 2499 2500‘-q’ 2501 Do not load the initialization file, ‘.guile’. This option only 2502 has an effect when running interactively; running scripts does not 2503 load the ‘.guile’ file. *Note Init File::. 2504 2505‘--listen[=P]’ 2506 While this program runs, listen on a local port or a path for REPL 2507 clients. If P starts with a number, it is assumed to be a local 2508 port on which to listen. If it starts with a forward slash, it is 2509 assumed to be the file name of a UNIX domain socket on which to 2510 listen. 2511 2512 If P is not given, the default is local port 37146. If you look at 2513 it upside down, it almost spells “Guile”. If you have netcat 2514 installed, you should be able to ‘nc localhost 37146’ and get a 2515 Guile prompt. Alternately you can fire up Emacs and connect to the 2516 process; see *note Using Guile in Emacs:: for more details. 2517 2518 Note: Opening a port allows anyone who can connect to that 2519 port to do anything Guile can do, as the user that the Guile 2520 process is running as. Do not use ‘--listen’ on multi-user 2521 machines. Of course, if you do not pass ‘--listen’ to Guile, 2522 no port will be opened. 2523 2524 Guile protects against the “HTTP inter-protocol exploitation 2525 attack” 2526 (https://en.wikipedia.org/wiki/Inter-protocol_exploitation), a 2527 scenario whereby an attacker can, via an HTML page, cause a 2528 web browser to send data to TCP servers listening on a 2529 loopback interface or private network. Nevertheless, you are 2530 advised to use UNIX domain sockets, as in 2531 ‘--listen=/some/local/file’, whenever possible. 2532 2533 That said, ‘--listen’ is great for interactive debugging and 2534 development. 2535 2536‘--auto-compile’ 2537 Compile source files automatically (default behavior). 2538 2539‘--fresh-auto-compile’ 2540 Treat the auto-compilation cache as invalid, forcing recompilation. 2541 2542‘--no-auto-compile’ 2543 Disable automatic source file compilation. 2544 2545‘--language=LANG’ 2546 For the remainder of the command line arguments, assume that files 2547 mentioned with ‘-l’ and expressions passed with ‘-c’ are written in 2548 LANG. LANG must be the name of one of the languages supported by 2549 the compiler (*note Compiler Tower::). When run interactively, set 2550 the REPL’s language to LANG (*note Using Guile Interactively::). 2551 2552 The default language is ‘scheme’; other interesting values include 2553 ‘elisp’ (for Emacs Lisp), and ‘ecmascript’. 2554 2555 The example below shows the evaluation of expressions in Scheme, 2556 Emacs Lisp, and ECMAScript: 2557 2558 guile -c "(apply + '(1 2))" 2559 guile --language=elisp -c "(= (funcall (symbol-function '+) 1 2) 3)" 2560 guile --language=ecmascript -c '(function (x) { return x * x; })(2);' 2561 2562 To load a file written in Scheme and one written in Emacs Lisp, and 2563 then start a Scheme REPL, type: 2564 2565 guile -l foo.scm --language=elisp -l foo.el --language=scheme 2566 2567‘-h, --help’ 2568 Display help on invoking Guile, and then exit. 2569 2570‘-v, --version’ 2571 Display the current version of Guile, and then exit. 2572 2573 2574File: guile.info, Node: Environment Variables, Prev: Command-line Options, Up: Invoking Guile 2575 25764.2.2 Environment Variables 2577--------------------------- 2578 2579The “environment” is a feature of the operating system; it consists of a 2580collection of variables with names and values. Each variable is called 2581an “environment variable” (or, sometimes, a “shell variable”); 2582environment variable names are case-sensitive, and it is conventional to 2583use upper-case letters only. The values are all text strings, even 2584those that are written as numerals. (Note that here we are referring to 2585names and values that are defined in the operating system shell from 2586which Guile is invoked. This is not the same as a Scheme environment 2587that is defined within a running instance of Guile. For a description 2588of Scheme environments, *note About Environments::.) 2589 2590 How to set environment variables before starting Guile depends on the 2591operating system and, especially, the shell that you are using. For 2592example, here is how to tell Guile to provide detailed warning messages 2593about deprecated features by setting ‘GUILE_WARN_DEPRECATED’ using Bash: 2594 2595 $ export GUILE_WARN_DEPRECATED="detailed" 2596 $ guile 2597 2598Or, detailed warnings can be turned on for a single invocation using: 2599 2600 $ env GUILE_WARN_DEPRECATED="detailed" guile 2601 2602 If you wish to retrieve or change the value of the shell environment 2603variables that affect the run-time behavior of Guile from within a 2604running instance of Guile, see *note Runtime Environment::. 2605 2606 Here are the environment variables that affect the run-time behavior 2607of Guile: 2608 2609‘GUILE_AUTO_COMPILE’ 2610 This is a flag that can be used to tell Guile whether or not to 2611 compile Scheme source files automatically. Starting with Guile 2612 2.0, Scheme source files will be compiled automatically, by 2613 default. 2614 2615 If a compiled (‘.go’) file corresponding to a ‘.scm’ file is not 2616 found or is not newer than the ‘.scm’ file, the ‘.scm’ file will be 2617 compiled on the fly, and the resulting ‘.go’ file stored away. An 2618 advisory note will be printed on the console. 2619 2620 Compiled files will be stored in the directory 2621 ‘$XDG_CACHE_HOME/guile/ccache’, where ‘XDG_CACHE_HOME’ defaults to 2622 the directory ‘$HOME/.cache’. This directory will be created if it 2623 does not already exist. 2624 2625 Note that this mechanism depends on the timestamp of the ‘.go’ file 2626 being newer than that of the ‘.scm’ file; if the ‘.scm’ or ‘.go’ 2627 files are moved after installation, care should be taken to 2628 preserve their original timestamps. 2629 2630 Set ‘GUILE_AUTO_COMPILE’ to zero (0), to prevent Scheme files from 2631 being compiled automatically. Set this variable to “fresh” to tell 2632 Guile to compile Scheme files whether they are newer than the 2633 compiled files or not. 2634 2635 *Note Compilation::. 2636 2637‘GUILE_HISTORY’ 2638 This variable names the file that holds the Guile REPL command 2639 history. You can specify a different history file by setting this 2640 environment variable. By default, the history file is 2641 ‘$HOME/.guile_history’. 2642 2643‘GUILE_INSTALL_LOCALE’ 2644 This is a flag that can be used to tell Guile whether or not to 2645 install the current locale at startup, via a call to ‘(setlocale 2646 LC_ALL "")’(1). *Note Locales::, for more information on locales. 2647 2648 You may explicitly indicate that you do not want to install the 2649 locale by setting ‘GUILE_INSTALL_LOCALE’ to ‘0’, or explicitly 2650 enable it by setting the variable to ‘1’. 2651 2652 Usually, installing the current locale is the right thing to do. 2653 It allows Guile to correctly parse and print strings with non-ASCII 2654 characters. Therefore, this option is on by default. 2655 2656‘GUILE_LOAD_COMPILED_PATH’ 2657 This variable may be used to augment the path that is searched for 2658 compiled Scheme files (‘.go’ files) when loading. Its value should 2659 be a colon-separated list of directories. If it contains the 2660 special path component ‘...’ (ellipsis), then the default path is 2661 put in place of the ellipsis, otherwise the default path is placed 2662 at the end. The result is stored in ‘%load-compiled-path’ (*note 2663 Load Paths::). 2664 2665 Here is an example using the Bash shell that adds the current 2666 directory, ‘.’, and the relative directory ‘../my-library’ to 2667 ‘%load-compiled-path’: 2668 2669 $ export GUILE_LOAD_COMPILED_PATH=".:../my-library" 2670 $ guile -c '(display %load-compiled-path) (newline)' 2671 (. ../my-library /usr/local/lib/guile/3.0/ccache) 2672 2673‘GUILE_LOAD_PATH’ 2674 This variable may be used to augment the path that is searched for 2675 Scheme files when loading. Its value should be a colon-separated 2676 list of directories. If it contains the special path component 2677 ‘...’ (ellipsis), then the default path is put in place of the 2678 ellipsis, otherwise the default path is placed at the end. The 2679 result is stored in ‘%load-path’ (*note Load Paths::). 2680 2681 Here is an example using the Bash shell that prepends the current 2682 directory to ‘%load-path’, and adds the relative directory 2683 ‘../srfi’ to the end: 2684 2685 $ env GUILE_LOAD_PATH=".:...:../srfi" \ 2686 guile -c '(display %load-path) (newline)' 2687 (. /usr/local/share/guile/3.0 \ 2688 /usr/local/share/guile/site/3.0 \ 2689 /usr/local/share/guile/site \ 2690 /usr/local/share/guile \ 2691 ../srfi) 2692 2693 (Note: The line breaks, above, are for documentation purposes only, 2694 and not required in the actual example.) 2695 2696‘GUILE_EXTENSIONS_PATH’ 2697 This variable may be used to augment the path that is searched for 2698 foreign libraries via ‘load-extension’, ‘dynamic-link’, 2699 ‘load-foreign-library’, or the like. Its value should be a 2700 colon-separated (semicolon on Windows) list of directories. *Note 2701 Foreign Libraries::. 2702 2703‘GUILE_WARN_DEPRECATED’ 2704 As Guile evolves, some features will be eliminated or replaced by 2705 newer features. To help users migrate their code as this evolution 2706 occurs, Guile will issue warning messages about code that uses 2707 features that have been marked for eventual elimination. 2708 ‘GUILE_WARN_DEPRECATED’ can be set to “no” to tell Guile not to 2709 display these warning messages, or set to “detailed” to tell Guile 2710 to display more lengthy messages describing the warning. *Note 2711 Deprecation::. 2712 2713‘HOME’ 2714 Guile uses the environment variable ‘HOME’, the name of your home 2715 directory, to locate various files, such as ‘.guile’ or 2716 ‘.guile_history’. 2717 2718‘GUILE_INSTALL_GMP_MEMORY_FUNCTIONS’ 2719 Guile uses the GNU multi-precision (GMP) library to implement its 2720 bigint support. It can use an included minimal version of GMP, or 2721 the system version, which may be more optimal. If Guile is the 2722 sole user of GMP in the process, Guile can tell GMP to allocate its 2723 digits using garbage-collected memory. This can be significantly 2724 faster. However this approach is unsafe if there are other 2725 libraries loaded that use libgmp, such as the GnuTLS library. The 2726 default is for Guile to do the fastest safe thing: use the garbage 2727 collector for GMP when using the included “mini-GMP”, but not 2728 otherwise. Set this variable to nonzero to force GMP to use 2729 garbage-collected memory, even when using system GC. 2730 2731‘GUILE_JIT_THRESHOLD’ 2732 Guile has a just-in-time (JIT) code generator that makes running 2733 Guile code fast. *Note Just-In-Time Native Code::, for more. The 2734 unit of code generation is the function. Each function has its own 2735 counter that gets incremented when the function is called and at 2736 each loop iteration in the function. When the counter exceeds the 2737 ‘GUILE_JIT_THRESHOLD’, the function will get JIT-compiled. Set 2738 ‘GUILE_JIT_THRESHOLD’ to ‘-1’ to disable JIT compilation, or ‘0’ to 2739 eagerly JIT-compile each function as it’s first seen. 2740 2741‘GUILE_JIT_LOG’ 2742 Set to ‘1’, ‘2’, or ‘3’ to give increasing amounts of logging for 2743 JIT compilation events. Used for debugging. 2744 2745‘GUILE_JIT_STOP_AFTER’ 2746 Though we have tested the JIT compiler as well as we can, it’s 2747 possible that it has bugs. If you suspect that Guile’s JIT 2748 compiler is causing your program to fail, set 2749 ‘GUILE_JIT_STOP_AFTER’ to a positive integer indicating the maximum 2750 number of functions to JIT-compile. By bisecting over the value of 2751 ‘GUILE_JIT_STOP_AFTER’, you can pinpoint the precise function that 2752 is being miscompiled. 2753 2754 ---------- Footnotes ---------- 2755 2756 (1) The ‘GUILE_INSTALL_LOCALE’ environment variable was ignored in 2757Guile versions prior to 2.0.9. 2758 2759 2760File: guile.info, Node: Guile Scripting, Next: Using Guile Interactively, Prev: Invoking Guile, Up: Programming in Scheme 2761 27624.3 Guile Scripting 2763=================== 2764 2765Like AWK, Perl, or any shell, Guile can interpret script files. A Guile 2766script is simply a file of Scheme code with some extra information at 2767the beginning which tells the operating system how to invoke Guile, and 2768then tells Guile how to handle the Scheme code. 2769 2770* Menu: 2771 2772* The Top of a Script File:: How to start a Guile script. 2773* The Meta Switch:: Passing complex argument lists to Guile 2774 from shell scripts. 2775* Command Line Handling:: Accessing the command line from a script. 2776* Scripting Examples:: 2777 2778 2779File: guile.info, Node: The Top of a Script File, Next: The Meta Switch, Up: Guile Scripting 2780 27814.3.1 The Top of a Script File 2782------------------------------ 2783 2784The first line of a Guile script must tell the operating system to use 2785Guile to evaluate the script, and then tell Guile how to go about doing 2786that. Here is the simplest case: 2787 2788 • The first two characters of the file must be ‘#!’. 2789 2790 The operating system interprets this to mean that the rest of the 2791 line is the name of an executable that can interpret the script. 2792 Guile, however, interprets these characters as the beginning of a 2793 multi-line comment, terminated by the characters ‘!#’ on a line by 2794 themselves. (This is an extension to the syntax described in R5RS, 2795 added to support shell scripts.) 2796 2797 • Immediately after those two characters must come the full pathname 2798 to the Guile interpreter. On most systems, this would be 2799 ‘/usr/local/bin/guile’. 2800 2801 • Then must come a space, followed by a command-line argument to pass 2802 to Guile; this should be ‘-s’. This switch tells Guile to run a 2803 script, instead of soliciting the user for input from the terminal. 2804 There are more elaborate things one can do here; see *note The Meta 2805 Switch::. 2806 2807 • Follow this with a newline. 2808 2809 • The second line of the script should contain only the characters 2810 ‘!#’ — just like the top of the file, but reversed. The operating 2811 system never reads this far, but Guile treats this as the end of 2812 the comment begun on the first line by the ‘#!’ characters. 2813 2814 • If this source code file is not ASCII or ISO-8859-1 encoded, a 2815 coding declaration such as ‘coding: utf-8’ should appear in a 2816 comment somewhere in the first five lines of the file: see *note 2817 Character Encoding of Source Files::. 2818 2819 • The rest of the file should be a Scheme program. 2820 2821 Guile reads the program, evaluating expressions in the order that 2822they appear. Upon reaching the end of the file, Guile exits. 2823 2824 2825File: guile.info, Node: The Meta Switch, Next: Command Line Handling, Prev: The Top of a Script File, Up: Guile Scripting 2826 28274.3.2 The Meta Switch 2828--------------------- 2829 2830Guile’s command-line switches allow the programmer to describe 2831reasonably complicated actions in scripts. Unfortunately, the POSIX 2832script invocation mechanism only allows one argument to appear on the 2833‘#!’ line after the path to the Guile executable, and imposes arbitrary 2834limits on that argument’s length. Suppose you wrote a script starting 2835like this: 2836 #!/usr/local/bin/guile -e main -s 2837 !# 2838 (define (main args) 2839 (map (lambda (arg) (display arg) (display " ")) 2840 (cdr args)) 2841 (newline)) 2842 The intended meaning is clear: load the file, and then call ‘main’ on 2843the command-line arguments. However, the system will treat everything 2844after the Guile path as a single argument — the string ‘"-e main -s"’ — 2845which is not what we want. 2846 2847 As a workaround, the meta switch ‘\’ allows the Guile programmer to 2848specify an arbitrary number of options without patching the kernel. If 2849the first argument to Guile is ‘\’, Guile will open the script file 2850whose name follows the ‘\’, parse arguments starting from the file’s 2851second line (according to rules described below), and substitute them 2852for the ‘\’ switch. 2853 2854 Working in concert with the meta switch, Guile treats the characters 2855‘#!’ as the beginning of a comment which extends through the next line 2856containing only the characters ‘!#’. This sort of comment may appear 2857anywhere in a Guile program, but it is most useful at the top of a file, 2858meshing magically with the POSIX script invocation mechanism. 2859 2860 Thus, consider a script named ‘/u/jimb/ekko’ which starts like this: 2861 #!/usr/local/bin/guile \ 2862 -e main -s 2863 !# 2864 (define (main args) 2865 (map (lambda (arg) (display arg) (display " ")) 2866 (cdr args)) 2867 (newline)) 2868 2869 Suppose a user invokes this script as follows: 2870 $ /u/jimb/ekko a b c 2871 2872 Here’s what happens: 2873 2874 • the operating system recognizes the ‘#!’ token at the top of the 2875 file, and rewrites the command line to: 2876 /usr/local/bin/guile \ /u/jimb/ekko a b c 2877 This is the usual behavior, prescribed by POSIX. 2878 2879 • When Guile sees the first two arguments, ‘\ /u/jimb/ekko’, it opens 2880 ‘/u/jimb/ekko’, parses the three arguments ‘-e’, ‘main’, and ‘-s’ 2881 from it, and substitutes them for the ‘\’ switch. Thus, Guile’s 2882 command line now reads: 2883 /usr/local/bin/guile -e main -s /u/jimb/ekko a b c 2884 2885 • Guile then processes these switches: it loads ‘/u/jimb/ekko’ as a 2886 file of Scheme code (treating the first three lines as a comment), 2887 and then performs the application ‘(main "/u/jimb/ekko" "a" "b" 2888 "c")’. 2889 2890 When Guile sees the meta switch ‘\’, it parses command-line argument 2891from the script file according to the following rules: 2892 2893 • Each space character terminates an argument. This means that two 2894 spaces in a row introduce an argument ‘""’. 2895 2896 • The tab character is not permitted (unless you quote it with the 2897 backslash character, as described below), to avoid confusion. 2898 2899 • The newline character terminates the sequence of arguments, and 2900 will also terminate a final non-empty argument. (However, a 2901 newline following a space will not introduce a final empty-string 2902 argument; it only terminates the argument list.) 2903 2904 • The backslash character is the escape character. It escapes 2905 backslash, space, tab, and newline. The ANSI C escape sequences 2906 like ‘\n’ and ‘\t’ are also supported. These produce argument 2907 constituents; the two-character combination ‘\n’ doesn’t act like a 2908 terminating newline. The escape sequence ‘\NNN’ for exactly three 2909 octal digits reads as the character whose ASCII code is NNN. As 2910 above, characters produced this way are argument constituents. 2911 Backslash followed by other characters is not allowed. 2912 2913 2914File: guile.info, Node: Command Line Handling, Next: Scripting Examples, Prev: The Meta Switch, Up: Guile Scripting 2915 29164.3.3 Command Line Handling 2917--------------------------- 2918 2919The ability to accept and handle command line arguments is very 2920important when writing Guile scripts to solve particular problems, such 2921as extracting information from text files or interfacing with existing 2922command line applications. This chapter describes how Guile makes 2923command line arguments available to a Guile script, and the utilities 2924that Guile provides to help with the processing of command line 2925arguments. 2926 2927 When a Guile script is invoked, Guile makes the command line 2928arguments accessible via the procedure ‘command-line’, which returns the 2929arguments as a list of strings. 2930 2931 For example, if the script 2932 2933 #! /usr/local/bin/guile -s 2934 !# 2935 (write (command-line)) 2936 (newline) 2937 2938is saved in a file ‘cmdline-test.scm’ and invoked using the command line 2939‘./cmdline-test.scm bar.txt -o foo -frumple grob’, the output is 2940 2941 ("./cmdline-test.scm" "bar.txt" "-o" "foo" "-frumple" "grob") 2942 2943 If the script invocation includes a ‘-e’ option, specifying a 2944procedure to call after loading the script, Guile will call that 2945procedure with ‘(command-line)’ as its argument. So a script that uses 2946‘-e’ doesn’t need to refer explicitly to ‘command-line’ in its code. 2947For example, the script above would have identical behaviour if it was 2948written instead like this: 2949 2950 #! /usr/local/bin/guile \ 2951 -e main -s 2952 !# 2953 (define (main args) 2954 (write args) 2955 (newline)) 2956 2957 (Note the use of the meta switch ‘\’ so that the script invocation 2958can include more than one Guile option: *Note The Meta Switch::.) 2959 2960 These scripts use the ‘#!’ POSIX convention so that they can be 2961executed using their own file names directly, as in the example command 2962line ‘./cmdline-test.scm bar.txt -o foo -frumple grob’. But they can 2963also be executed by typing out the implied Guile command line in full, 2964as in: 2965 2966 $ guile -s ./cmdline-test.scm bar.txt -o foo -frumple grob 2967 2968or 2969 2970 $ guile -e main -s ./cmdline-test2.scm bar.txt -o foo -frumple grob 2971 2972 Even when a script is invoked using this longer form, the arguments 2973that the script receives are the same as if it had been invoked using 2974the short form. Guile ensures that the ‘(command-line)’ or ‘-e’ 2975arguments are independent of how the script is invoked, by stripping off 2976the arguments that Guile itself processes. 2977 2978 A script is free to parse and handle its command line arguments in 2979any way that it chooses. Where the set of possible options and 2980arguments is complex, however, it can get tricky to extract all the 2981options, check the validity of given arguments, and so on. This task 2982can be greatly simplified by taking advantage of the module ‘(ice-9 2983getopt-long)’, which is distributed with Guile, *Note getopt-long::. 2984 2985 2986File: guile.info, Node: Scripting Examples, Prev: Command Line Handling, Up: Guile Scripting 2987 29884.3.4 Scripting Examples 2989------------------------ 2990 2991To start with, here are some examples of invoking Guile directly: 2992 2993‘guile -- a b c’ 2994 Run Guile interactively; ‘(command-line)’ will return 2995 ‘("/usr/local/bin/guile" "a" "b" "c")’. 2996 2997‘guile -s /u/jimb/ex2 a b c’ 2998 Load the file ‘/u/jimb/ex2’; ‘(command-line)’ will return 2999 ‘("/u/jimb/ex2" "a" "b" "c")’. 3000 3001‘guile -c '(write %load-path) (newline)'’ 3002 Write the value of the variable ‘%load-path’, print a newline, and 3003 exit. 3004 3005‘guile -e main -s /u/jimb/ex4 foo’ 3006 Load the file ‘/u/jimb/ex4’, and then call the function ‘main’, 3007 passing it the list ‘("/u/jimb/ex4" "foo")’. 3008 3009‘guile -e '(ex4)' -s /u/jimb/ex4.scm foo’ 3010 Load the file ‘/u/jimb/ex4.scm’, and then call the function ‘main’ 3011 from the module ’(ex4)’, passing it the list ‘("/u/jimb/ex4" 3012 "foo")’. 3013 3014‘guile -l first -ds -l last -s script’ 3015 Load the files ‘first’, ‘script’, and ‘last’, in that order. The 3016 ‘-ds’ switch says when to process the ‘-s’ switch. For a more 3017 motivated example, see the scripts below. 3018 3019 Here is a very simple Guile script: 3020 #!/usr/local/bin/guile -s 3021 !# 3022 (display "Hello, world!") 3023 (newline) 3024 The first line marks the file as a Guile script. When the user 3025invokes it, the system runs ‘/usr/local/bin/guile’ to interpret the 3026script, passing ‘-s’, the script’s filename, and any arguments given to 3027the script as command-line arguments. When Guile sees ‘-s SCRIPT’, it 3028loads SCRIPT. Thus, running this program produces the output: 3029 Hello, world! 3030 3031 Here is a script which prints the factorial of its argument: 3032 #!/usr/local/bin/guile -s 3033 !# 3034 (define (fact n) 3035 (if (zero? n) 1 3036 (* n (fact (- n 1))))) 3037 3038 (display (fact (string->number (cadr (command-line))))) 3039 (newline) 3040 In action: 3041 $ ./fact 5 3042 120 3043 $ 3044 3045 However, suppose we want to use the definition of ‘fact’ in this file 3046from another script. We can’t simply ‘load’ the script file, and then 3047use ‘fact’’s definition, because the script will try to compute and 3048display a factorial when we load it. To avoid this problem, we might 3049write the script this way: 3050 3051 #!/usr/local/bin/guile \ 3052 -e main -s 3053 !# 3054 (define (fact n) 3055 (if (zero? n) 1 3056 (* n (fact (- n 1))))) 3057 3058 (define (main args) 3059 (display (fact (string->number (cadr args)))) 3060 (newline)) 3061 This version packages the actions the script should perform in a 3062function, ‘main’. This allows us to load the file purely for its 3063definitions, without any extraneous computation taking place. Then we 3064used the meta switch ‘\’ and the entry point switch ‘-e’ to tell Guile 3065to call ‘main’ after loading the script. 3066 $ ./fact 50 3067 30414093201713378043612608166064768844377641568960512000000000000 3068 3069 Suppose that we now want to write a script which computes the 3070‘choose’ function: given a set of M distinct objects, ‘(choose N M)’ is 3071the number of distinct subsets containing N objects each. It’s easy to 3072write ‘choose’ given ‘fact’, so we might write the script this way: 3073 3074 #!/usr/local/bin/guile \ 3075 -l fact -e main -s 3076 !# 3077 (define (choose n m) 3078 (/ (fact m) (* (fact (- m n)) (fact n)))) 3079 3080 (define (main args) 3081 (let ((n (string->number (cadr args))) 3082 (m (string->number (caddr args)))) 3083 (display (choose n m)) 3084 (newline))) 3085 3086 The command-line arguments here tell Guile to first load the file 3087‘fact’, and then run the script, with ‘main’ as the entry point. In 3088other words, the ‘choose’ script can use definitions made in the ‘fact’ 3089script. Here are some sample runs: 3090 $ ./choose 0 4 3091 1 3092 $ ./choose 1 4 3093 4 3094 $ ./choose 2 4 3095 6 3096 $ ./choose 3 4 3097 4 3098 $ ./choose 4 4 3099 1 3100 $ ./choose 50 100 3101 100891344545564193334812497256 3102 3103 To call a specific procedure from a given module, we can use the 3104special form ‘(@ (MODULE) PROCEDURE)’: 3105 3106 #!/usr/local/bin/guile \ 3107 -l fact -e (@ (fac) main) -s 3108 !# 3109 (define-module (fac) 3110 #:export (main)) 3111 3112 (define (choose n m) 3113 (/ (fact m) (* (fact (- m n)) (fact n)))) 3114 3115 (define (main args) 3116 (let ((n (string->number (cadr args))) 3117 (m (string->number (caddr args)))) 3118 (display (choose n m)) 3119 (newline))) 3120 3121 We can use ‘@@’ to invoke non-exported procedures. For exported 3122procedures, we can simplify this call with the shorthand ‘(MODULE)’: 3123 3124 #!/usr/local/bin/guile \ 3125 -l fact -e (fac) -s 3126 !# 3127 (define-module (fac) 3128 #:export (main)) 3129 3130 (define (choose n m) 3131 (/ (fact m) (* (fact (- m n)) (fact n)))) 3132 3133 (define (main args) 3134 (let ((n (string->number (cadr args))) 3135 (m (string->number (caddr args)))) 3136 (display (choose n m)) 3137 (newline))) 3138 3139 For maximum portability, we can instead use the shell to execute 3140‘guile’ with specified command line arguments. Here we need to take 3141care to quote the command arguments correctly: 3142 3143 #!/usr/bin/env sh 3144 exec guile -l fact -e '(@ (fac) main)' -s "$0" "$@" 3145 !# 3146 (define-module (fac) 3147 #:export (main)) 3148 3149 (define (choose n m) 3150 (/ (fact m) (* (fact (- m n)) (fact n)))) 3151 3152 (define (main args) 3153 (let ((n (string->number (cadr args))) 3154 (m (string->number (caddr args)))) 3155 (display (choose n m)) 3156 (newline))) 3157 3158 Finally, seasoned scripters are probably missing a mention of 3159subprocesses. In Bash, for example, most shell scripts run other 3160programs like ‘sed’ or the like to do the actual work. 3161 3162 In Guile it’s often possible get everything done within Guile itself, 3163so do give that a try first. But if you just need to run a program and 3164wait for it to finish, use ‘system*’. If you need to run a sub-program 3165and capture its output, or give it input, use ‘open-pipe’. *Note 3166Processes::, and *Note Pipes::, for more information. 3167 3168 3169File: guile.info, Node: Using Guile Interactively, Next: Using Guile in Emacs, Prev: Guile Scripting, Up: Programming in Scheme 3170 31714.4 Using Guile Interactively 3172============================= 3173 3174When you start up Guile by typing just ‘guile’, without a ‘-c’ argument 3175or the name of a script to execute, you get an interactive interpreter 3176where you can enter Scheme expressions, and Guile will evaluate them and 3177print the results for you. Here are some simple examples. 3178 3179 scheme@(guile-user)> (+ 3 4 5) 3180 $1 = 12 3181 scheme@(guile-user)> (display "Hello world!\n") 3182 Hello world! 3183 scheme@(guile-user)> (values 'a 'b) 3184 $2 = a 3185 $3 = b 3186 3187This mode of use is called a “REPL”, which is short for “Read-Eval-Print 3188Loop”, because the Guile interpreter first reads the expression that you 3189have typed, then evaluates it, and then prints the result. 3190 3191 The prompt shows you what language and module you are in. In this 3192case, the current language is ‘scheme’, and the current module is 3193‘(guile-user)’. *Note Other Languages::, for more information on 3194Guile’s support for languages other than Scheme. 3195 3196* Menu: 3197 3198* Init File:: 3199* Readline:: 3200* Value History:: 3201* REPL Commands:: 3202* Error Handling:: 3203* Interactive Debugging:: 3204 3205 3206File: guile.info, Node: Init File, Next: Readline, Up: Using Guile Interactively 3207 32084.4.1 The Init File, ‘~/.guile’ 3209------------------------------- 3210 3211When run interactively, Guile will load a local initialization file from 3212‘~/.guile’. This file should contain Scheme expressions for evaluation. 3213 3214 This facility lets the user customize their interactive Guile 3215environment, pulling in extra modules or parameterizing the REPL 3216implementation. 3217 3218 To run Guile without loading the init file, use the ‘-q’ command-line 3219option. 3220 3221 3222File: guile.info, Node: Readline, Next: Value History, Prev: Init File, Up: Using Guile Interactively 3223 32244.4.2 Readline 3225-------------- 3226 3227To make it easier for you to repeat and vary previously entered 3228expressions, or to edit the expression that you’re typing in, Guile can 3229use the GNU Readline library. This is not enabled by default because of 3230licensing reasons, but all you need to activate Readline is the 3231following pair of lines. 3232 3233 scheme@(guile-user)> (use-modules (ice-9 readline)) 3234 scheme@(guile-user)> (activate-readline) 3235 3236 It’s a good idea to put these two lines (without the 3237‘scheme@(guile-user)>’ prompts) in your ‘.guile’ file. *Note Init 3238File::, for more on ‘.guile’. 3239 3240 3241File: guile.info, Node: Value History, Next: REPL Commands, Prev: Readline, Up: Using Guile Interactively 3242 32434.4.3 Value History 3244------------------- 3245 3246Just as Readline helps you to reuse a previous input line, “value 3247history” allows you to use the _result_ of a previous evaluation in a 3248new expression. When value history is enabled, each evaluation result 3249is automatically assigned to the next in the sequence of variables ‘$1’, 3250‘$2’, .... You can then use these variables in subsequent expressions. 3251 3252 scheme@(guile-user)> (iota 10) 3253 $1 = (0 1 2 3 4 5 6 7 8 9) 3254 scheme@(guile-user)> (apply * (cdr $1)) 3255 $2 = 362880 3256 scheme@(guile-user)> (sqrt $2) 3257 $3 = 602.3952191045344 3258 scheme@(guile-user)> (cons $2 $1) 3259 $4 = (362880 0 1 2 3 4 5 6 7 8 9) 3260 3261 Value history is enabled by default, because Guile’s REPL imports the 3262‘(ice-9 history)’ module. Value history may be turned off or on within 3263the repl, using the options interface: 3264 3265 scheme@(guile-user)> ,option value-history #f 3266 scheme@(guile-user)> 'foo 3267 foo 3268 scheme@(guile-user)> ,option value-history #t 3269 scheme@(guile-user)> 'bar 3270 $5 = bar 3271 3272 Note that previously recorded values are still accessible, even if 3273value history is off. In rare cases, these references to past 3274computations can cause Guile to use too much memory. One may clear 3275these values, possibly enabling garbage collection, via the 3276‘clear-value-history!’ procedure, described below. 3277 3278 The programmatic interface to value history is in a module: 3279 3280 (use-modules (ice-9 history)) 3281 3282 -- Scheme Procedure: value-history-enabled? 3283 Return true if value history is enabled, or false otherwise. 3284 3285 -- Scheme Procedure: enable-value-history! 3286 Turn on value history, if it was off. 3287 3288 -- Scheme Procedure: disable-value-history! 3289 Turn off value history, if it was on. 3290 3291 -- Scheme Procedure: clear-value-history! 3292 Clear the value history. If the stored values are not captured by 3293 some other data structure or closure, they may then be reclaimed by 3294 the garbage collector. 3295 3296 3297File: guile.info, Node: REPL Commands, Next: Error Handling, Prev: Value History, Up: Using Guile Interactively 3298 32994.4.4 REPL Commands 3300------------------- 3301 3302The REPL exists to read expressions, evaluate them, and then print their 3303results. But sometimes one wants to tell the REPL to evaluate an 3304expression in a different way, or to do something else altogether. A 3305user can affect the way the REPL works with a “REPL command”. 3306 3307 The previous section had an example of a command, in the form of 3308‘,option’. 3309 3310 scheme@(guile-user)> ,option value-history #t 3311 3312Commands are distinguished from expressions by their initial comma 3313(‘,’). Since a comma cannot begin an expression in most languages, it 3314is an effective indicator to the REPL that the following text forms a 3315command, not an expression. 3316 3317 REPL commands are convenient because they are always there. Even if 3318the current module doesn’t have a binding for ‘pretty-print’, one can 3319always ‘,pretty-print’. 3320 3321 The following sections document the various commands, grouped 3322together by functionality. Many of the commands have abbreviations; see 3323the online help (‘,help’) for more information. 3324 3325* Menu: 3326 3327* Help Commands:: 3328* Module Commands:: 3329* Language Commands:: 3330* Compile Commands:: 3331* Profile Commands:: 3332* Debug Commands:: 3333* Inspect Commands:: 3334* System Commands:: 3335 3336 3337File: guile.info, Node: Help Commands, Next: Module Commands, Up: REPL Commands 3338 33394.4.4.1 Help Commands 3340..................... 3341 3342When Guile starts interactively, it notifies the user that help can be 3343had by typing ‘,help’. Indeed, ‘help’ is a command, and a particularly 3344useful one, as it allows the user to discover the rest of the commands. 3345 3346 -- REPL Command: help [‘all’ | group | ‘[-c]’ command] 3347 Show help. 3348 3349 With one argument, tries to look up the argument as a group name, 3350 giving help on that group if successful. Otherwise tries to look 3351 up the argument as a command, giving help on the command. 3352 3353 If there is a command whose name is also a group name, use the ‘-c 3354 COMMAND’ form to give help on the command instead of the group. 3355 3356 Without any argument, a list of help commands and command groups 3357 are displayed. 3358 3359 -- REPL Command: show [topic] 3360 Gives information about Guile. 3361 3362 With one argument, tries to show a particular piece of information; 3363 currently supported topics are ‘warranty’ (or ‘w’), ‘copying’ (or 3364 ‘c’), and ‘version’ (or ‘v’). 3365 3366 Without any argument, a list of topics is displayed. 3367 3368 -- REPL Command: apropos regexp 3369 Find bindings/modules/packages. 3370 3371 -- REPL Command: describe obj 3372 Show description/documentation. 3373 3374 3375File: guile.info, Node: Module Commands, Next: Language Commands, Prev: Help Commands, Up: REPL Commands 3376 33774.4.4.2 Module Commands 3378....................... 3379 3380 -- REPL Command: module [module] 3381 Change modules / Show current module. 3382 3383 -- REPL Command: import module ... 3384 Import modules / List those imported. 3385 3386 -- REPL Command: load file 3387 Load a file in the current module. 3388 3389 -- REPL Command: reload [module] 3390 Reload the given module, or the current module if none was given. 3391 3392 -- REPL Command: binding 3393 List current bindings. 3394 3395 -- REPL Command: in module expression 3396 -- REPL Command: in module command arg ... 3397 Evaluate an expression, or alternatively, execute another 3398 meta-command in the context of a module. For example, ‘,in (foo 3399 bar) ,binding’ will show the bindings in the module ‘(foo bar)’. 3400 3401 3402File: guile.info, Node: Language Commands, Next: Compile Commands, Prev: Module Commands, Up: REPL Commands 3403 34044.4.4.3 Language Commands 3405......................... 3406 3407 -- REPL Command: language language 3408 Change languages. 3409 3410 3411File: guile.info, Node: Compile Commands, Next: Profile Commands, Prev: Language Commands, Up: REPL Commands 3412 34134.4.4.4 Compile Commands 3414........................ 3415 3416 -- REPL Command: compile exp 3417 Generate compiled code. 3418 3419 -- REPL Command: compile-file file 3420 Compile a file. 3421 3422 -- REPL Command: expand exp 3423 Expand any macros in a form. 3424 3425 -- REPL Command: optimize exp 3426 Run the optimizer on a piece of code and print the result. 3427 3428 -- REPL Command: disassemble exp 3429 Disassemble a compiled procedure. 3430 3431 -- REPL Command: disassemble-file file 3432 Disassemble a file. 3433 3434 3435File: guile.info, Node: Profile Commands, Next: Debug Commands, Prev: Compile Commands, Up: REPL Commands 3436 34374.4.4.5 Profile Commands 3438........................ 3439 3440 -- REPL Command: time exp 3441 Time execution. 3442 3443 -- REPL Command: profile exp [#:hz hz=100] [#:count-calls? 3444 count-calls?=#f] [#:display-style display-style=list] 3445 Profile execution of an expression. This command compiled EXP and 3446 then runs it within the statprof profiler, passing all keyword 3447 options to the ‘statprof’ procedure. For more on statprof and on 3448 the the options available to this command, *Note Statprof::. 3449 3450 -- REPL Command: trace exp [#:width w] [#:max-indent i] 3451 Trace execution. 3452 3453 By default, the trace will limit its width to the width of your 3454 terminal, or WIDTH if specified. Nested procedure invocations will 3455 be printed farther to the right, though if the width of the 3456 indentation passes the MAX-INDENT, the indentation is abbreviated. 3457 3458 These REPL commands can also be called as regular functions in scheme 3459code on including the ‘(ice-9 time)’ module. 3460 3461 3462File: guile.info, Node: Debug Commands, Next: Inspect Commands, Prev: Profile Commands, Up: REPL Commands 3463 34644.4.4.6 Debug Commands 3465...................... 3466 3467These debugging commands are only available within a recursive REPL; 3468they do not work at the top level. 3469 3470 -- REPL Command: backtrace [count] [#:width w] [#:full? f] 3471 Print a backtrace. 3472 3473 Print a backtrace of all stack frames, or innermost COUNT frames. 3474 If COUNT is negative, the last COUNT frames will be shown. 3475 3476 -- REPL Command: up [count] 3477 Select a calling stack frame. 3478 3479 Select and print stack frames that called this one. An argument 3480 says how many frames up to go. 3481 3482 -- REPL Command: down [count] 3483 Select a called stack frame. 3484 3485 Select and print stack frames called by this one. An argument says 3486 how many frames down to go. 3487 3488 -- REPL Command: frame [idx] 3489 Show a frame. 3490 3491 Show the selected frame. With an argument, select a frame by 3492 index, then show it. 3493 3494 -- REPL Command: locals 3495 Show local variables. 3496 3497 Show locally-bound variables in the selected frame. 3498 3499 -- REPL Command: error-message 3500 -- REPL Command: error 3501 Show error message. 3502 3503 Display the message associated with the error that started the 3504 current debugging REPL. 3505 3506 -- REPL Command: registers 3507 Show the VM registers associated with the current frame. 3508 3509 *Note Stack Layout::, for more information on VM stack frames. 3510 3511 -- REPL Command: width [cols] 3512 Sets the number of display columns in the output of ‘,backtrace’ 3513 and ‘,locals’ to COLS. If COLS is not given, the width of the 3514 terminal is used. 3515 3516 The next 3 commands work at any REPL. 3517 3518 -- REPL Command: break proc 3519 Set a breakpoint at PROC. 3520 3521 -- REPL Command: break-at-source file line 3522 Set a breakpoint at the given source location. 3523 3524 -- REPL Command: tracepoint proc 3525 Set a tracepoint on the given procedure. This will cause all calls 3526 to the procedure to print out a tracing message. *Note Tracing 3527 Traps::, for more information. 3528 3529 The rest of the commands in this subsection all apply only when the 3530stack is “continuable” — in other words when it makes sense for the 3531program that the stack comes from to continue running. Usually this 3532means that the program stopped because of a trap or a breakpoint. 3533 3534 -- REPL Command: step 3535 Tell the debugged program to step to the next source location. 3536 3537 -- REPL Command: next 3538 Tell the debugged program to step to the next source location in 3539 the same frame. (See *note Traps:: for the details of how this 3540 works.) 3541 3542 -- REPL Command: finish 3543 Tell the program being debugged to continue running until the 3544 completion of the current stack frame, and at that time to print 3545 the result and reenter the REPL. 3546 3547 3548File: guile.info, Node: Inspect Commands, Next: System Commands, Prev: Debug Commands, Up: REPL Commands 3549 35504.4.4.7 Inspect Commands 3551........................ 3552 3553 -- REPL Command: inspect exp 3554 Inspect the result(s) of evaluating EXP. 3555 3556 -- REPL Command: pretty-print exp 3557 Pretty-print the result(s) of evaluating EXP. 3558 3559 3560File: guile.info, Node: System Commands, Prev: Inspect Commands, Up: REPL Commands 3561 35624.4.4.8 System Commands 3563....................... 3564 3565 -- REPL Command: gc 3566 Garbage collection. 3567 3568 -- REPL Command: statistics 3569 Display statistics. 3570 3571 -- REPL Command: option [name] [exp] 3572 With no arguments, lists all options. With one argument, shows the 3573 current value of the NAME option. With two arguments, sets the 3574 NAME option to the result of evaluating the Scheme expression EXP. 3575 3576 -- REPL Command: quit 3577 Quit this session. 3578 3579 Current REPL options include: 3580 3581‘compile-options’ 3582 The options used when compiling expressions entered at the REPL. 3583 *Note Compilation::, for more on compilation options. 3584‘interp’ 3585 Whether to interpret or compile expressions given at the REPL, if 3586 such a choice is available. Off by default (indicating 3587 compilation). 3588‘prompt’ 3589 A customized REPL prompt. ‘#f’ by default, indicating the default 3590 prompt. 3591‘print’ 3592 A procedure of two arguments used to print the result of evaluating 3593 each expression. The arguments are the current REPL and the value 3594 to print. By default, ‘#f’, to use the default procedure. 3595‘value-history’ 3596 Whether value history is on or not. *Note Value History::. 3597‘on-error’ 3598 What to do when an error happens. By default, ‘debug’, meaning to 3599 enter the debugger. Other values include ‘backtrace’, to show a 3600 backtrace without entering the debugger, or ‘report’, to simply 3601 show a short error printout. 3602 3603 Default values for REPL options may be set using 3604‘repl-default-option-set!’ from ‘(system repl common)’: 3605 3606 -- Scheme Procedure: repl-default-option-set! key value 3607 Set the default value of a REPL option. This function is 3608 particularly useful in a user’s init file. *Note Init File::. 3609 3610 3611File: guile.info, Node: Error Handling, Next: Interactive Debugging, Prev: REPL Commands, Up: Using Guile Interactively 3612 36134.4.5 Error Handling 3614-------------------- 3615 3616When code being evaluated from the REPL hits an error, Guile enters a 3617new prompt, allowing you to inspect the context of the error. 3618 3619 scheme@(guile-user)> (map string-append '("a" "b") '("c" #\d)) 3620 ERROR: In procedure string-append: 3621 ERROR: Wrong type (expecting string): #\d 3622 Entering a new prompt. Type `,bt' for a backtrace or `,q' to continue. 3623 scheme@(guile-user) [1]> 3624 3625 The new prompt runs inside the old one, in the dynamic context of the 3626error. It is a recursive REPL, augmented with a reified representation 3627of the stack, ready for debugging. 3628 3629 ‘,backtrace’ (abbreviated ‘,bt’) displays the Scheme call stack at 3630the point where the error occurred: 3631 3632 scheme@(guile-user) [1]> ,bt 3633 1 (map #<procedure string-append _> ("a" "b") ("c" #\d)) 3634 0 (string-append "b" #\d) 3635 3636 In the above example, the backtrace doesn’t have much source 3637information, as ‘map’ and ‘string-append’ are both primitives. But in 3638the general case, the space on the left of the backtrace indicates the 3639line and column in which a given procedure calls another. 3640 3641 You can exit a recursive REPL in the same way that you exit any REPL: 3642via ‘(quit)’, ‘,quit’ (abbreviated ‘,q’), or ‘C-d’, among other options. 3643 3644 3645File: guile.info, Node: Interactive Debugging, Prev: Error Handling, Up: Using Guile Interactively 3646 36474.4.6 Interactive Debugging 3648--------------------------- 3649 3650A recursive debugging REPL exposes a number of other meta-commands that 3651inspect the state of the computation at the time of the error. These 3652commands allow you to 3653 3654 • display the Scheme call stack at the point where the error 3655 occurred; 3656 3657 • move up and down the call stack, to see in detail the expression 3658 being evaluated, or the procedure being applied, in each “frame”; 3659 and 3660 3661 • examine the values of variables and expressions in the context of 3662 each frame. 3663 3664*Note Debug Commands::, for documentation of the individual commands. 3665This section aims to give more of a walkthrough of a typical debugging 3666session. 3667 3668 First, we’re going to need a good error. Let’s try to macroexpand 3669the expression ‘(unquote foo)’, outside of a ‘quasiquote’ form, and see 3670how the macroexpander reports this error. 3671 3672 scheme@(guile-user)> (macroexpand '(unquote foo)) 3673 ERROR: In procedure macroexpand: 3674 ERROR: unquote: expression not valid outside of quasiquote in (unquote foo) 3675 Entering a new prompt. Type `,bt' for a backtrace or `,q' to continue. 3676 scheme@(guile-user) [1]> 3677 3678 The ‘backtrace’ command, which can also be invoked as ‘bt’, displays 3679the call stack (aka backtrace) at the point where the debugger was 3680entered: 3681 3682 scheme@(guile-user) [1]> ,bt 3683 In ice-9/psyntax.scm: 3684 1130:21 3 (chi-top (unquote foo) () ((top)) e (eval) (hygiene #)) 3685 1071:30 2 (syntax-type (unquote foo) () ((top)) #f #f (# #) #f) 3686 1368:28 1 (chi-macro #<procedure de9360 at ice-9/psyntax.scm...> ...) 3687 In unknown file: 3688 0 (scm-error syntax-error macroexpand "~a: ~a in ~a" # #f) 3689 3690 A call stack consists of a sequence of stack “frames”, with each 3691frame describing one procedure which is waiting to do something with the 3692values returned by another. Here we see that there are four frames on 3693the stack. 3694 3695 Note that ‘macroexpand’ is not on the stack – it must have made a 3696tail call to ‘chi-top’, as indeed we would find if we searched 3697‘ice-9/psyntax.scm’ for its definition. 3698 3699 When you enter the debugger, the innermost frame is selected, which 3700means that the commands for getting information about the “current” 3701frame, or for evaluating expressions in the context of the current 3702frame, will do so by default with respect to the innermost frame. To 3703select a different frame, so that these operations will apply to it 3704instead, use the ‘up’, ‘down’ and ‘frame’ commands like this: 3705 3706 scheme@(guile-user) [1]> ,up 3707 In ice-9/psyntax.scm: 3708 1368:28 1 (chi-macro #<procedure de9360 at ice-9/psyntax.scm...> ...) 3709 scheme@(guile-user) [1]> ,frame 3 3710 In ice-9/psyntax.scm: 3711 1130:21 3 (chi-top (unquote foo) () ((top)) e (eval) (hygiene #)) 3712 scheme@(guile-user) [1]> ,down 3713 In ice-9/psyntax.scm: 3714 1071:30 2 (syntax-type (unquote foo) () ((top)) #f #f (# #) #f) 3715 3716 Perhaps we’re interested in what’s going on in frame 2, so we take a 3717look at its local variables: 3718 3719 scheme@(guile-user) [1]> ,locals 3720 Local variables: 3721 $1 = e = (unquote foo) 3722 $2 = r = () 3723 $3 = w = ((top)) 3724 $4 = s = #f 3725 $5 = rib = #f 3726 $6 = mod = (hygiene guile-user) 3727 $7 = for-car? = #f 3728 $8 = first = unquote 3729 $9 = ftype = macro 3730 $10 = fval = #<procedure de9360 at ice-9/psyntax.scm:2817:2 (x)> 3731 $11 = fe = unquote 3732 $12 = fw = ((top)) 3733 $13 = fs = #f 3734 $14 = fmod = (hygiene guile-user) 3735 3736 All of the values are accessible by their value-history names (‘$N’): 3737 3738 scheme@(guile-user) [1]> $10 3739 $15 = #<procedure de9360 at ice-9/psyntax.scm:2817:2 (x)> 3740 3741 We can even invoke the procedure at the REPL directly: 3742 3743 scheme@(guile-user) [1]> ($10 'not-going-to-work) 3744 ERROR: In procedure macroexpand: 3745 ERROR: source expression failed to match any pattern in not-going-to-work 3746 Entering a new prompt. Type `,bt' for a backtrace or `,q' to continue. 3747 3748 Well at this point we’ve caused an error within an error. Let’s just 3749quit back to the top level: 3750 3751 scheme@(guile-user) [2]> ,q 3752 scheme@(guile-user) [1]> ,q 3753 scheme@(guile-user)> 3754 3755 Finally, as a word to the wise: hackers close their REPL prompts with 3756‘C-d’. 3757 3758 3759File: guile.info, Node: Using Guile in Emacs, Next: Using Guile Tools, Prev: Using Guile Interactively, Up: Programming in Scheme 3760 37614.5 Using Guile in Emacs 3762======================== 3763 3764Any text editor can edit Scheme, but some are better than others. Emacs 3765is the best, of course, and not just because it is a fine text editor. 3766Emacs has good support for Scheme out of the box, with sensible 3767indentation rules, parenthesis-matching, syntax highlighting, and even a 3768set of keybindings for structural editing, allowing navigation, 3769cut-and-paste, and transposition operations that work on balanced 3770S-expressions. 3771 3772 As good as it is, though, two things will vastly improve your 3773experience with Emacs and Guile. 3774 3775 The first is Taylor Campbell’s Paredit 3776(http://www.emacswiki.org/emacs/ParEdit). You should not code in any 3777dialect of Lisp without Paredit. (They say that unopinionated writing 3778is boring—hence this tone—but it’s the truth, regardless.) Paredit is 3779the bee’s knees. 3780 3781 The second is José Antonio Ortega Ruiz’s Geiser 3782(http://www.nongnu.org/geiser/). Geiser complements Emacs’ 3783‘scheme-mode’ with tight integration to running Guile processes via a 3784‘comint-mode’ REPL buffer. 3785 3786 Of course there are keybindings to switch to the REPL, and a good 3787REPL environment, but Geiser goes beyond that, providing: 3788 3789 • Form evaluation in the context of the current file’s module. 3790 • Macro expansion. 3791 • File/module loading and/or compilation. 3792 • Namespace-aware identifier completion (including local bindings, 3793 names visible in the current module, and module names). 3794 • Autodoc: the echo area shows information about the signature of the 3795 procedure/macro around point automatically. 3796 • Jump to definition of identifier at point. 3797 • Access to documentation (including docstrings when the 3798 implementation provides it). 3799 • Listings of identifiers exported by a given module. 3800 • Listings of callers/callees of procedures. 3801 • Rudimentary support for debugging and error navigation. 3802 • Support for multiple, simultaneous REPLs. 3803 3804 See Geiser’s web page at <http://www.nongnu.org/geiser/>, for more 3805information. 3806 3807 3808File: guile.info, Node: Using Guile Tools, Next: Installing Site Packages, Prev: Using Guile in Emacs, Up: Programming in Scheme 3809 38104.6 Using Guile Tools 3811===================== 3812 3813Guile also comes with a growing number of command-line utilities: a 3814compiler, a disassembler, some module inspectors, and in the future, a 3815system to install Guile packages from the internet. These tools may be 3816invoked using the ‘guild’ program. 3817 3818 $ guild compile -o foo.go foo.scm 3819 wrote `foo.go' 3820 3821 This program used to be called ‘guile-tools’ up to Guile version 38222.0.1, and for backward compatibility it still may be called as such. 3823However we changed the name to ‘guild’, not only because it is 3824pleasantly shorter and easier to read, but also because this tool will 3825serve to bind Guile wizards together, by allowing hackers to share code 3826with each other using a CPAN-like system. 3827 3828 *Note Compilation::, for more on ‘guild compile’. 3829 3830 A complete list of guild scripts can be had by invoking ‘guild list’, 3831or simply ‘guild’. 3832 3833 3834File: guile.info, Node: Installing Site Packages, Next: Distributing Guile Code, Prev: Using Guile Tools, Up: Programming in Scheme 3835 38364.7 Installing Site Packages 3837============================ 3838 3839At some point, you will probably want to share your code with other 3840people. To do so effectively, it is important to follow a set of common 3841conventions, to make it easy for the user to install and use your 3842package. 3843 3844 The first thing to do is to install your Scheme files where Guile can 3845find them. When Guile goes to find a Scheme file, it will search a 3846“load path” to find the file: first in Guile’s own path, then in paths 3847for “site packages”. A site package is any Scheme code that is 3848installed and not part of Guile itself. *Note Load Paths::, for more on 3849load paths. 3850 3851 There are several site paths, for historical reasons, but the one 3852that should generally be used can be obtained by invoking the 3853‘%site-dir’ procedure. *Note Build Config::. If Guile 3.0 is installed 3854on your system in ‘/usr/’, then ‘(%site-dir)’ will be 3855‘/usr/share/guile/site/3.0’. Scheme files should be installed there. 3856 3857 If you do not install compiled ‘.go’ files, Guile will compile your 3858modules and programs when they are first used, and cache them in the 3859user’s home directory. *Note Compilation::, for more on 3860auto-compilation. However, it is better to compile the files before 3861they are installed, and to just copy the files to a place that Guile can 3862find them. 3863 3864 As with Scheme files, Guile searches a path to find compiled ‘.go’ 3865files, the ‘%load-compiled-path’. By default, this path has two 3866entries: a path for Guile’s files, and a path for site packages. You 3867should install your ‘.go’ files into the latter directory, whose value 3868is returned by invoking the ‘%site-ccache-dir’ procedure. As in the 3869previous example, if Guile 3.0 is installed on your system in ‘/usr/’, 3870then ‘(%site-ccache-dir)’ site packages will be 3871‘/usr/lib/guile/3.0/site-ccache’. 3872 3873 Note that a ‘.go’ file will only be loaded in preference to a ‘.scm’ 3874file if it is newer. For that reason, you should install your Scheme 3875files first, and your compiled files second. *Note Load Paths::, for 3876more on the loading process. 3877 3878 Finally, although this section is only about Scheme, sometimes you 3879need to install C extensions too. Shared libraries should be installed 3880in the “extensions dir”. This value can be had from the build config 3881(*note Build Config::). Again, if Guile 3.0 is installed on your system 3882in ‘/usr/’, then the extensions dir will be 3883‘/usr/lib/guile/3.0/extensions’. 3884 3885 3886File: guile.info, Node: Distributing Guile Code, Prev: Installing Site Packages, Up: Programming in Scheme 3887 38884.8 Distributing Guile Code 3889=========================== 3890 3891There’s a tool that doesn’t come bundled with Guile and yet can be very 3892useful in your day to day experience with it. This tool is Hall 3893(https://gitlab.com/a-sassmannshausen/guile-hall). 3894 3895 Hall helps you create, manage, and package your Guile projects 3896through a simple command-line interface. When you start a new project, 3897Hall creates a folder containing a scaffold of your new project. It 3898contains a directory for your tests, for your libraries, for your 3899scripts and for your documentation. This means you immediately know 3900where to put the files you are hacking on. 3901 3902 In addition, the scaffold will include your basic “Autotools” setup, 3903so you don’t have to take care of that yourself (*note (autoconf)The GNU 3904Build System::, for more information on the GNU “Autotools”). Having 3905Autotools set up with your project means you can immediately start 3906hacking on your project without worrying about whether your code will 3907work on other people’s computers. Hall can also generate package 3908definitions for the GNU Guix package manager, making it easy for Guix 3909users to install it. 3910 3911 3912File: guile.info, Node: Programming in C, Next: API Reference, Prev: Programming in Scheme, Up: Top 3913 39145 Programming in C 3915****************** 3916 3917This part of the manual explains the general concepts that you need to 3918understand when interfacing to Guile from C. You will learn about how 3919the latent typing of Scheme is embedded into the static typing of C, how 3920the garbage collection of Guile is made available to C code, and how 3921continuations influence the control flow in a C program. 3922 3923 This knowledge should make it straightforward to add new functions to 3924Guile that can be called from Scheme. Adding new data types is also 3925possible and is done by defining “foreign objects”. 3926 3927 The *note Programming Overview:: section of this part contains 3928general musings and guidelines about programming with Guile. It 3929explores different ways to design a program around Guile, or how to 3930embed Guile into existing programs. 3931 3932 For a pedagogical yet detailed explanation of how the data 3933representation of Guile is implemented, *Note Data Representation::. 3934You don’t need to know the details given there to use Guile from C, but 3935they are useful when you want to modify Guile itself or when you are 3936just curious about how it is all done. 3937 3938 For detailed reference information on the variables, functions etc. 3939that make up Guile’s application programming interface (API), *Note API 3940Reference::. 3941 3942* Menu: 3943 3944* Parallel Installations:: Finding the right Guile. 3945* Linking Programs With Guile:: More precisely, with the libguile library. 3946* Linking Guile with Libraries:: To extend Guile itself. 3947* General Libguile Concepts:: General concepts for using libguile. 3948* Defining New Foreign Object Types:: Adding new types to Guile. 3949* Function Snarfing:: A way to define new functions. 3950* Programming Overview:: An overview of Guile programming. 3951* Autoconf Support:: Putting m4 to good use. 3952 3953 3954File: guile.info, Node: Parallel Installations, Next: Linking Programs With Guile, Up: Programming in C 3955 39565.1 Parallel Installations 3957========================== 3958 3959Guile provides strong API and ABI stability guarantees during stable 3960series, so that if a user writes a program against Guile version 2.2.3, 3961it will be compatible with some future version 2.2.7. We say in this 3962case that 2.2 is the “effective version”, composed of the major and 3963minor versions, in this case 2 and 2. 3964 3965 Users may install multiple effective versions of Guile, with each 3966version’s headers, libraries, and Scheme files under their own 3967directories. This provides the necessary stability guarantee for users, 3968while also allowing Guile developers to evolve the language and its 3969implementation. 3970 3971 However, parallel installability does have a down-side, in that users 3972need to know which version of Guile to ask for, when they build against 3973Guile. Guile solves this problem by installing a file to be read by the 3974‘pkg-config’ utility, a tool to query installed packages by name. Guile 3975encodes the version into its pkg-config name, so that users can ask for 3976‘guile-2.2’ or ‘guile-3.0’, as appropriate. 3977 3978 For effective version 3.0, for example, you would invoke ‘pkg-config 3979--cflags --libs guile-3.0’ to get the compilation and linking flags 3980necessary to link to version 3.0 of Guile. You would typically run 3981‘pkg-config’ during the configuration phase of your program and use the 3982obtained information in the Makefile. 3983 3984 Guile’s ‘pkg-config’ file, ‘guile-3.0.pc’, defines additional useful 3985variables: 3986 3987‘sitedir’ 3988 The default directory where Guile looks for Scheme source and 3989 compiled files (*note %site-dir: Installing Site Packages.). Run 3990 ‘pkg-config guile-3.0 --variable=sitedir’ to see its value. *Note 3991 GUILE_SITE_DIR: Autoconf Macros, for more on how to use it from 3992 Autoconf. 3993 3994‘extensiondir’ 3995 The default directory where Guile looks for extensions—i.e., shared 3996 libraries providing additional features (*note Foreign 3997 Extensions::). Run ‘pkg-config guile-3.0 --variable=extensiondir’ 3998 to see its value. 3999 4000‘guile’ 4001‘guild’ 4002 The absolute file name of the ‘guile’ and ‘guild’ commands(1). Run 4003 ‘pkg-config guile-3.0 --variable=guile’ or ‘--variable=guild’ to 4004 see their value. 4005 4006 These variables allow users to deal with program name 4007 transformations that may be specified when configuring Guile with 4008 ‘--program-transform-name’, ‘--program-suffix’, or 4009 ‘--program-prefix’ (*note (autoconf)Transformation Options::). 4010 4011See the ‘pkg-config’ man page, for more information, or its web site, 4012<http://pkg-config.freedesktop.org/>. *Note Autoconf Support::, for 4013more on checking for Guile from within a ‘configure.ac’ file. 4014 4015 ---------- Footnotes ---------- 4016 4017 (1) The ‘guile’ and ‘guild’ variables defined starting from Guile 4018version 2.0.12. 4019 4020 4021File: guile.info, Node: Linking Programs With Guile, Next: Linking Guile with Libraries, Prev: Parallel Installations, Up: Programming in C 4022 40235.2 Linking Programs With Guile 4024=============================== 4025 4026This section covers the mechanics of linking your program with Guile on 4027a typical POSIX system. 4028 4029 The header file ‘<libguile.h>’ provides declarations for all of 4030Guile’s functions and constants. You should ‘#include’ it at the head 4031of any C source file that uses identifiers described in this manual. 4032Once you’ve compiled your source files, you need to link them against 4033the Guile object code library, ‘libguile’. 4034 4035 As noted in the previous section, ‘<libguile.h>’ is not in the 4036default search path for headers. The following command lines give 4037respectively the C compilation and link flags needed to build programs 4038using Guile 3.0: 4039 4040 pkg-config guile-3.0 --cflags 4041 pkg-config guile-3.0 --libs 4042 4043* Menu: 4044 4045* Guile Initialization Functions:: What to call first. 4046* A Sample Guile Main Program:: Sources and makefiles. 4047 4048 4049File: guile.info, Node: Guile Initialization Functions, Next: A Sample Guile Main Program, Up: Linking Programs With Guile 4050 40515.2.1 Guile Initialization Functions 4052------------------------------------ 4053 4054To initialize Guile, you can use one of several functions. The first, 4055‘scm_with_guile’, is the most portable way to initialize Guile. It will 4056initialize Guile when necessary and then call a function that you can 4057specify. Multiple threads can call ‘scm_with_guile’ concurrently and it 4058can also be called more than once in a given thread. The global state 4059of Guile will survive from one call of ‘scm_with_guile’ to the next. 4060Your function is called from within ‘scm_with_guile’ since the garbage 4061collector of Guile needs to know where the stack of each thread is. 4062 4063 A second function, ‘scm_init_guile’, initializes Guile for the 4064current thread. When it returns, you can use the Guile API in the 4065current thread. This function employs some non-portable magic to learn 4066about stack bounds and might thus not be available on all platforms. 4067 4068 One common way to use Guile is to write a set of C functions which 4069perform some useful task, make them callable from Scheme, and then link 4070the program with Guile. This yields a Scheme interpreter just like 4071‘guile’, but augmented with extra functions for some specific 4072application — a special-purpose scripting language. 4073 4074 In this situation, the application should probably process its 4075command-line arguments in the same manner as the stock Guile 4076interpreter. To make that straightforward, Guile provides the 4077‘scm_boot_guile’ and ‘scm_shell’ function. 4078 4079 For more about these functions, see *note Initialization::. 4080 4081 4082File: guile.info, Node: A Sample Guile Main Program, Prev: Guile Initialization Functions, Up: Linking Programs With Guile 4083 40845.2.2 A Sample Guile Main Program 4085--------------------------------- 4086 4087Here is ‘simple-guile.c’, source code for a ‘main’ and an ‘inner_main’ 4088function that will produce a complete Guile interpreter. 4089 4090 /* simple-guile.c --- Start Guile from C. */ 4091 4092 #include <libguile.h> 4093 4094 static void 4095 inner_main (void *closure, int argc, char **argv) 4096 { 4097 /* preparation */ 4098 scm_shell (argc, argv); 4099 /* after exit */ 4100 } 4101 4102 int 4103 main (int argc, char **argv) 4104 { 4105 scm_boot_guile (argc, argv, inner_main, 0); 4106 return 0; /* never reached, see inner_main */ 4107 } 4108 4109 The ‘main’ function calls ‘scm_boot_guile’ to initialize Guile, 4110passing it ‘inner_main’. Once ‘scm_boot_guile’ is ready, it invokes 4111‘inner_main’, which calls ‘scm_shell’ to process the command-line 4112arguments in the usual way. 4113 41145.2.3 Building the Example with Make 4115------------------------------------ 4116 4117Here is a Makefile which you can use to compile the example program. It 4118uses ‘pkg-config’ to learn about the necessary compiler and linker 4119flags. 4120 # Use GCC, if you have it installed. 4121 CC=gcc 4122 4123 # Tell the C compiler where to find <libguile.h> 4124 CFLAGS=`pkg-config --cflags guile-3.0` 4125 4126 # Tell the linker what libraries to use and where to find them. 4127 LIBS=`pkg-config --libs guile-3.0` 4128 4129 simple-guile: simple-guile.o 4130 ${CC} simple-guile.o ${LIBS} -o simple-guile 4131 4132 simple-guile.o: simple-guile.c 4133 ${CC} -c ${CFLAGS} simple-guile.c 4134 41355.2.4 Building the Example with Autoconf 4136---------------------------------------- 4137 4138If you are using the GNU Autoconf package to make your application more 4139portable, Autoconf will settle many of the details in the Makefile 4140automatically, making it much simpler and more portable; we recommend 4141using Autoconf with Guile. Here is a ‘configure.ac’ file for 4142‘simple-guile’ that uses the standard ‘PKG_CHECK_MODULES’ macro to check 4143for Guile. Autoconf will process this file into a ‘configure’ script. 4144We recommend invoking Autoconf via the ‘autoreconf’ utility. 4145 4146 AC_INIT(simple-guile.c) 4147 4148 # Find a C compiler. 4149 AC_PROG_CC 4150 4151 # Check for Guile 4152 PKG_CHECK_MODULES([GUILE], [guile-3.0]) 4153 4154 # Generate a Makefile, based on the results. 4155 AC_OUTPUT(Makefile) 4156 4157 Run ‘autoreconf -vif’ to generate ‘configure’. 4158 4159 Here is a ‘Makefile.in’ template, from which the ‘configure’ script 4160produces a Makefile customized for the host system: 4161 # The configure script fills in these values. 4162 CC=@CC@ 4163 CFLAGS=@GUILE_CFLAGS@ 4164 LIBS=@GUILE_LIBS@ 4165 4166 simple-guile: simple-guile.o 4167 ${CC} simple-guile.o ${LIBS} -o simple-guile 4168 simple-guile.o: simple-guile.c 4169 ${CC} -c ${CFLAGS} simple-guile.c 4170 4171 The developer should use Autoconf to generate the ‘configure’ script 4172from the ‘configure.ac’ template, and distribute ‘configure’ with the 4173application. Here’s how a user might go about building the application: 4174 4175 $ ls 4176 Makefile.in configure* configure.ac simple-guile.c 4177 $ ./configure 4178 checking for gcc... ccache gcc 4179 checking whether the C compiler works... yes 4180 checking for C compiler default output file name... a.out 4181 checking for suffix of executables... 4182 checking whether we are cross compiling... no 4183 checking for suffix of object files... o 4184 checking whether we are using the GNU C compiler... yes 4185 checking whether ccache gcc accepts -g... yes 4186 checking for ccache gcc option to accept ISO C89... none needed 4187 checking for pkg-config... /usr/bin/pkg-config 4188 checking pkg-config is at least version 0.9.0... yes 4189 checking for GUILE... yes 4190 configure: creating ./config.status 4191 config.status: creating Makefile 4192 $ make 4193 [...] 4194 $ ./simple-guile 4195 guile> (+ 1 2 3) 4196 6 4197 guile> (getpwnam "jimb") 4198 #("jimb" "83Z7d75W2tyJQ" 4008 10 "Jim Blandy" "/u/jimb" 4199 "/usr/local/bin/bash") 4200 guile> (exit) 4201 $ 4202 4203 4204File: guile.info, Node: Linking Guile with Libraries, Next: General Libguile Concepts, Prev: Linking Programs With Guile, Up: Programming in C 4205 42065.3 Linking Guile with Libraries 4207================================ 4208 4209The previous section has briefly explained how to write programs that 4210make use of an embedded Guile interpreter. But sometimes, all you want 4211to do is make new primitive procedures and data types available to the 4212Scheme programmer. Writing a new version of ‘guile’ is inconvenient in 4213this case and it would in fact make the life of the users of your new 4214features needlessly hard. 4215 4216 For example, suppose that there is a program ‘guile-db’ that is a 4217version of Guile with additional features for accessing a database. 4218People who want to write Scheme programs that use these features would 4219have to use ‘guile-db’ instead of the usual ‘guile’ program. Now 4220suppose that there is also a program ‘guile-gtk’ that extends Guile with 4221access to the popular Gtk+ toolkit for graphical user interfaces. 4222People who want to write GUIs in Scheme would have to use ‘guile-gtk’. 4223Now, what happens when you want to write a Scheme application that uses 4224a GUI to let the user access a database? You would have to write a 4225_third_ program that incorporates both the database stuff and the GUI 4226stuff. This might not be easy (because ‘guile-gtk’ might be a quite 4227obscure program, say) and taking this example further makes it easy to 4228see that this approach can not work in practice. 4229 4230 It would have been much better if both the database features and the 4231GUI feature had been provided as libraries that can just be linked with 4232‘guile’. Guile makes it easy to do just this, and we encourage you to 4233make your extensions to Guile available as libraries whenever possible. 4234 4235 You write the new primitive procedures and data types in the normal 4236fashion, and link them into a shared library instead of into a 4237stand-alone program. The shared library can then be loaded dynamically 4238by Guile. 4239 4240* Menu: 4241 4242* A Sample Guile Extension:: 4243 4244 4245File: guile.info, Node: A Sample Guile Extension, Up: Linking Guile with Libraries 4246 42475.3.1 A Sample Guile Extension 4248------------------------------ 4249 4250This section explains how to make the Bessel functions of the C library 4251available to Scheme. First we need to write the appropriate glue code 4252to convert the arguments and return values of the functions from Scheme 4253to C and back. Additionally, we need a function that will add them to 4254the set of Guile primitives. Because this is just an example, we will 4255only implement this for the ‘j0’ function. 4256 4257 Consider the following file ‘bessel.c’. 4258 4259 #include <math.h> 4260 #include <libguile.h> 4261 4262 SCM 4263 j0_wrapper (SCM x) 4264 { 4265 return scm_from_double (j0 (scm_to_double (x))); 4266 } 4267 4268 void 4269 init_bessel () 4270 { 4271 scm_c_define_gsubr ("j0", 1, 0, 0, j0_wrapper); 4272 } 4273 4274 This C source file needs to be compiled into a shared library. Here 4275is how to do it on GNU/Linux: 4276 4277 gcc `pkg-config --cflags guile-3.0` \ 4278 -shared -o libguile-bessel.so -fPIC bessel.c 4279 4280 For creating shared libraries portably, we recommend the use of GNU 4281Libtool (*note Introduction: (libtool)Top.). 4282 4283 A shared library can be loaded into a running Guile process with the 4284function ‘load-extension’. In addition to the name of the library to 4285load, this function also expects the name of a function from that 4286library that will be called to initialize it. For our example, we are 4287going to call the function ‘init_bessel’ which will make ‘j0_wrapper’ 4288available to Scheme programs with the name ‘j0’. Note that we do not 4289specify a filename extension such as ‘.so’ when invoking 4290‘load-extension’. The right extension for the host platform will be 4291provided automatically. 4292 4293 (load-extension "libguile-bessel" "init_bessel") 4294 (j0 2) 4295 ⇒ 0.223890779141236 4296 4297 For this to work, ‘load-extension’ must be able to find 4298‘libguile-bessel’, of course. It will look in the places that are usual 4299for your operating system, and it will additionally look into the 4300directories listed in the ‘LTDL_LIBRARY_PATH’ environment variable. 4301 4302 To see how these Guile extensions via shared libraries relate to the 4303module system, *Note Putting Extensions into Modules::. 4304 4305 4306File: guile.info, Node: General Libguile Concepts, Next: Defining New Foreign Object Types, Prev: Linking Guile with Libraries, Up: Programming in C 4307 43085.4 General concepts for using libguile 4309======================================= 4310 4311When you want to embed the Guile Scheme interpreter into your program or 4312library, you need to link it against the ‘libguile’ library (*note 4313Linking Programs With Guile::). Once you have done this, your C code 4314has access to a number of data types and functions that can be used to 4315invoke the interpreter, or make new functions that you have written in C 4316available to be called from Scheme code, among other things. 4317 4318 Scheme is different from C in a number of significant ways, and Guile 4319tries to make the advantages of Scheme available to C as well. Thus, in 4320addition to a Scheme interpreter, libguile also offers dynamic types, 4321garbage collection, continuations, arithmetic on arbitrary sized 4322numbers, and other things. 4323 4324 The two fundamental concepts are dynamic types and garbage 4325collection. You need to understand how libguile offers them to C 4326programs in order to use the rest of libguile. Also, the more general 4327control flow of Scheme caused by continuations needs to be dealt with. 4328 4329 Running asynchronous signal handlers and multi-threading is known to 4330C code already, but there are of course a few additional rules when 4331using them together with libguile. 4332 4333* Menu: 4334 4335* Dynamic Types:: Dynamic Types. 4336* Garbage Collection:: Garbage Collection. 4337* Control Flow:: Control Flow. 4338* Asynchronous Signals:: Asynchronous Signals 4339* Multi-Threading:: Multi-Threading 4340 4341 4342File: guile.info, Node: Dynamic Types, Next: Garbage Collection, Up: General Libguile Concepts 4343 43445.4.1 Dynamic Types 4345------------------- 4346 4347Scheme is a dynamically-typed language; this means that the system 4348cannot, in general, determine the type of a given expression at compile 4349time. Types only become apparent at run time. Variables do not have 4350fixed types; a variable may hold a pair at one point, an integer at the 4351next, and a thousand-element vector later. Instead, values, not 4352variables, have fixed types. 4353 4354 In order to implement standard Scheme functions like ‘pair?’ and 4355‘string?’ and provide garbage collection, the representation of every 4356value must contain enough information to accurately determine its type 4357at run time. Often, Scheme systems also use this information to 4358determine whether a program has attempted to apply an operation to an 4359inappropriately typed value (such as taking the ‘car’ of a string). 4360 4361 Because variables, pairs, and vectors may hold values of any type, 4362Scheme implementations use a uniform representation for values — a 4363single type large enough to hold either a complete value or a pointer to 4364a complete value, along with the necessary typing information. 4365 4366 In Guile, this uniform representation of all Scheme values is the C 4367type ‘SCM’. This is an opaque type and its size is typically equivalent 4368to that of a pointer to ‘void’. Thus, ‘SCM’ values can be passed around 4369efficiently and they take up reasonably little storage on their own. 4370 4371 The most important rule is: You never access a ‘SCM’ value directly; 4372you only pass it to functions or macros defined in libguile. 4373 4374 As an obvious example, although a ‘SCM’ variable can contain 4375integers, you can of course not compute the sum of two ‘SCM’ values by 4376adding them with the C ‘+’ operator. You must use the libguile function 4377‘scm_sum’. 4378 4379 Less obvious and therefore more important to keep in mind is that you 4380also cannot directly test ‘SCM’ values for trueness. In Scheme, the 4381value ‘#f’ is considered false and of course a ‘SCM’ variable can 4382represent that value. But there is no guarantee that the ‘SCM’ 4383representation of ‘#f’ looks false to C code as well. You need to use 4384‘scm_is_true’ or ‘scm_is_false’ to test a ‘SCM’ value for trueness or 4385falseness, respectively. 4386 4387 You also can not directly compare two ‘SCM’ values to find out 4388whether they are identical (that is, whether they are ‘eq?’ in Scheme 4389terms). You need to use ‘scm_is_eq’ for this. 4390 4391 The one exception is that you can directly assign a ‘SCM’ value to a 4392‘SCM’ variable by using the C ‘=’ operator. 4393 4394 The following (contrived) example shows how to do it right. It 4395implements a function of two arguments (A and FLAG) that returns A+1 if 4396FLAG is true, else it returns A unchanged. 4397 4398 SCM 4399 my_incrementing_function (SCM a, SCM flag) 4400 { 4401 SCM result; 4402 4403 if (scm_is_true (flag)) 4404 result = scm_sum (a, scm_from_int (1)); 4405 else 4406 result = a; 4407 4408 return result; 4409 } 4410 4411 Often, you need to convert between ‘SCM’ values and appropriate C 4412values. For example, we needed to convert the integer ‘1’ to its ‘SCM’ 4413representation in order to add it to A. Libguile provides many function 4414to do these conversions, both from C to ‘SCM’ and from ‘SCM’ to C. 4415 4416 The conversion functions follow a common naming pattern: those that 4417make a ‘SCM’ value from a C value have names of the form ‘scm_from_TYPE 4418(...)’ and those that convert a ‘SCM’ value to a C value use the form 4419‘scm_to_TYPE (...)’. 4420 4421 However, it is best to avoid converting values when you can. When 4422you must combine C values and ‘SCM’ values in a computation, it is often 4423better to convert the C values to ‘SCM’ values and do the computation by 4424using libguile functions than to the other way around (converting ‘SCM’ 4425to C and doing the computation some other way). 4426 4427 As a simple example, consider this version of 4428‘my_incrementing_function’ from above: 4429 4430 SCM 4431 my_other_incrementing_function (SCM a, SCM flag) 4432 { 4433 int result; 4434 4435 if (scm_is_true (flag)) 4436 result = scm_to_int (a) + 1; 4437 else 4438 result = scm_to_int (a); 4439 4440 return scm_from_int (result); 4441 } 4442 4443 This version is much less general than the original one: it will only 4444work for values A that can fit into a ‘int’. The original function will 4445work for all values that Guile can represent and that ‘scm_sum’ can 4446understand, including integers bigger than ‘long long’, floating point 4447numbers, complex numbers, and new numerical types that have been added 4448to Guile by third-party libraries. 4449 4450 Also, computing with ‘SCM’ is not necessarily inefficient. Small 4451integers will be encoded directly in the ‘SCM’ value, for example, and 4452do not need any additional memory on the heap. See *note Data 4453Representation:: to find out the details. 4454 4455 Some special ‘SCM’ values are available to C code without needing to 4456convert them from C values: 4457 4458Scheme value C representation 4459#f SCM_BOOL_F 4460#t SCM_BOOL_T 4461() SCM_EOL 4462 4463 In addition to ‘SCM’, Guile also defines the related type 4464‘scm_t_bits’. This is an unsigned integral type of sufficient size to 4465hold all information that is directly contained in a ‘SCM’ value. The 4466‘scm_t_bits’ type is used internally by Guile to do all the bit 4467twiddling explained in *note Data Representation::, but you will 4468encounter it occasionally in low-level user code as well. 4469 4470 4471File: guile.info, Node: Garbage Collection, Next: Control Flow, Prev: Dynamic Types, Up: General Libguile Concepts 4472 44735.4.2 Garbage Collection 4474------------------------ 4475 4476As explained above, the ‘SCM’ type can represent all Scheme values. 4477Some values fit entirely into a ‘SCM’ value (such as small integers), 4478but other values require additional storage in the heap (such as strings 4479and vectors). This additional storage is managed automatically by 4480Guile. You don’t need to explicitly deallocate it when a ‘SCM’ value is 4481no longer used. 4482 4483 Two things must be guaranteed so that Guile is able to manage the 4484storage automatically: it must know about all blocks of memory that have 4485ever been allocated for Scheme values, and it must know about all Scheme 4486values that are still being used. Given this knowledge, Guile can 4487periodically free all blocks that have been allocated but are not used 4488by any active Scheme values. This activity is called “garbage 4489collection”. 4490 4491 Guile’s garbage collector will automatically discover references to 4492‘SCM’ objects that originate in global variables, static data sections, 4493function arguments or local variables on the C and Scheme stacks, and 4494values in machine registers. Other references to ‘SCM’ objects, such as 4495those in other random data structures in the C heap that contain fields 4496of type ‘SCM’, can be made visible to the garbage collector by calling 4497the functions ‘scm_gc_protect_object’ or ‘scm_permanent_object’. 4498Collectively, these values form the “root set” of garbage collection; 4499any value on the heap that is referenced directly or indirectly by a 4500member of the root set is preserved, and all other objects are eligible 4501for reclamation. 4502 4503 In Guile, garbage collection has two logical phases: the “mark 4504phase”, in which the collector discovers the set of all live objects, 4505and the “sweep phase”, in which the collector reclaims the resources 4506associated with dead objects. The mark phase pauses the program and 4507traces all ‘SCM’ object references, starting with the root set. The 4508sweep phase actually runs concurrently with the main program, 4509incrementally reclaiming memory as needed by allocation. 4510 4511 In the mark phase, the garbage collector traces the Scheme stack and 4512heap “precisely”. Because the Scheme stack and heap are managed by 4513Guile, Guile can know precisely where in those data structures it might 4514find references to other heap objects. This is not the case, 4515unfortunately, for pointers on the C stack and static data segment. 4516Instead of requiring the user to inform Guile about all variables in C 4517that might point to heap objects, Guile traces the C stack and static 4518data segment “conservatively”. That is to say, Guile just treats every 4519word on the C stack and every C global variable as a potential reference 4520in to the Scheme heap(1). Any value that looks like a pointer to a 4521GC-managed object is treated as such, whether it actually is a reference 4522or not. Thus, scanning the C stack and static data segment is 4523guaranteed to find all actual references, but it might also find words 4524that only accidentally look like references. These “false positives” 4525might keep ‘SCM’ objects alive that would otherwise be considered dead. 4526While this might waste memory, keeping an object around longer than it 4527strictly needs to is harmless. This is why this technique is called 4528“conservative garbage collection”. In practice, the wasted memory seems 4529to be no problem, as the static C root set is almost always finite and 4530small, given that the Scheme stack is separate from the C stack. 4531 4532 The stack of every thread is scanned in this way and the registers of 4533the CPU and all other memory locations where local variables or function 4534parameters might show up are included in this scan as well. 4535 4536 The consequence of the conservative scanning is that you can just 4537declare local variables and function parameters of type ‘SCM’ and be 4538sure that the garbage collector will not free the corresponding objects. 4539 4540 However, a local variable or function parameter is only protected as 4541long as it is really on the stack (or in some register). As an 4542optimization, the C compiler might reuse its location for some other 4543value and the ‘SCM’ object would no longer be protected. Normally, this 4544leads to exactly the right behavior: the compiler will only overwrite a 4545reference when it is no longer needed and thus the object becomes 4546unprotected precisely when the reference disappears, just as wanted. 4547 4548 There are situations, however, where a ‘SCM’ object needs to be 4549around longer than its reference from a local variable or function 4550parameter. This happens, for example, when you retrieve some pointer 4551from a foreign object and work with that pointer directly. The 4552reference to the ‘SCM’ foreign object might be dead after the pointer 4553has been retrieved, but the pointer itself (and the memory pointed to) 4554is still in use and thus the foreign object must be protected. The 4555compiler does not know about this connection and might overwrite the 4556‘SCM’ reference too early. 4557 4558 To get around this problem, you can use ‘scm_remember_upto_here_1’ 4559and its cousins. It will keep the compiler from overwriting the 4560reference. *Note Foreign Object Memory Management::. 4561 4562 ---------- Footnotes ---------- 4563 4564 (1) Note that Guile does not scan the C heap for references, so a 4565reference to a ‘SCM’ object from a memory segment allocated with 4566‘malloc’ will have to use some other means to keep the ‘SCM’ object 4567alive. *Note Garbage Collection Functions::. 4568 4569 4570File: guile.info, Node: Control Flow, Next: Asynchronous Signals, Prev: Garbage Collection, Up: General Libguile Concepts 4571 45725.4.3 Control Flow 4573------------------ 4574 4575Scheme has a more general view of program flow than C, both locally and 4576non-locally. 4577 4578 Controlling the local flow of control involves things like gotos, 4579loops, calling functions and returning from them. Non-local control 4580flow refers to situations where the program jumps across one or more 4581levels of function activations without using the normal call or return 4582operations. 4583 4584 The primitive means of C for local control flow is the ‘goto’ 4585statement, together with ‘if’. Loops done with ‘for’, ‘while’ or ‘do’ 4586could in principle be rewritten with just ‘goto’ and ‘if’. In Scheme, 4587the primitive means for local control flow is the _function call_ 4588(together with ‘if’). Thus, the repetition of some computation in a 4589loop is ultimately implemented by a function that calls itself, that is, 4590by recursion. 4591 4592 This approach is theoretically very powerful since it is easier to 4593reason formally about recursion than about gotos. In C, using recursion 4594exclusively would not be practical, though, since it would eat up the 4595stack very quickly. In Scheme, however, it is practical: function calls 4596that appear in a “tail position” do not use any additional stack space 4597(*note Tail Calls::). 4598 4599 A function call is in a tail position when it is the last thing the 4600calling function does. The value returned by the called function is 4601immediately returned from the calling function. In the following 4602example, the call to ‘bar-1’ is in a tail position, while the call to 4603‘bar-2’ is not. (The call to ‘1-’ in ‘foo-2’ is in a tail position, 4604though.) 4605 4606 (define (foo-1 x) 4607 (bar-1 (1- x))) 4608 4609 (define (foo-2 x) 4610 (1- (bar-2 x))) 4611 4612 Thus, when you take care to recurse only in tail positions, the 4613recursion will only use constant stack space and will be as good as a 4614loop constructed from gotos. 4615 4616 Scheme offers a few syntactic abstractions (‘do’ and “named” ‘let’) 4617that make writing loops slightly easier. 4618 4619 But only Scheme functions can call other functions in a tail 4620position: C functions can not. This matters when you have, say, two 4621functions that call each other recursively to form a common loop. The 4622following (unrealistic) example shows how one might go about determining 4623whether a non-negative integer N is even or odd. 4624 4625 (define (my-even? n) 4626 (cond ((zero? n) #t) 4627 (else (my-odd? (1- n))))) 4628 4629 (define (my-odd? n) 4630 (cond ((zero? n) #f) 4631 (else (my-even? (1- n))))) 4632 4633 Because the calls to ‘my-even?’ and ‘my-odd?’ are in tail positions, 4634these two procedures can be applied to arbitrary large integers without 4635overflowing the stack. (They will still take a lot of time, of course.) 4636 4637 However, when one or both of the two procedures would be rewritten in 4638C, it could no longer call its companion in a tail position (since C 4639does not have this concept). You might need to take this consideration 4640into account when deciding which parts of your program to write in 4641Scheme and which in C. 4642 4643 In addition to calling functions and returning from them, a Scheme 4644program can also exit non-locally from a function so that the control 4645flow returns directly to an outer level. This means that some functions 4646might not return at all. 4647 4648 Even more, it is not only possible to jump to some outer level of 4649control, a Scheme program can also jump back into the middle of a 4650function that has already exited. This might cause some functions to 4651return more than once. 4652 4653 In general, these non-local jumps are done by invoking 4654“continuations” that have previously been captured using 4655‘call-with-current-continuation’. Guile also offers a slightly 4656restricted set of functions, ‘catch’ and ‘throw’, that can only be used 4657for non-local exits. This restriction makes them more efficient. Error 4658reporting (with the function ‘error’) is implemented by invoking 4659‘throw’, for example. The functions ‘catch’ and ‘throw’ belong to the 4660topic of “exceptions”. 4661 4662 Since Scheme functions can call C functions and vice versa, C code 4663can experience the more general control flow of Scheme as well. It is 4664possible that a C function will not return at all, or will return more 4665than once. While C does offer ‘setjmp’ and ‘longjmp’ for non-local 4666exits, it is still an unusual thing for C code. In contrast, non-local 4667exits are very common in Scheme, mostly to report errors. 4668 4669 You need to be prepared for the non-local jumps in the control flow 4670whenever you use a function from ‘libguile’: it is best to assume that 4671any ‘libguile’ function might signal an error or run a pending signal 4672handler (which in turn can do arbitrary things). 4673 4674 It is often necessary to take cleanup actions when the control leaves 4675a function non-locally. Also, when the control returns non-locally, 4676some setup actions might be called for. For example, the Scheme 4677function ‘with-output-to-port’ needs to modify the global state so that 4678‘current-output-port’ returns the port passed to ‘with-output-to-port’. 4679The global output port needs to be reset to its previous value when 4680‘with-output-to-port’ returns normally or when it is exited non-locally. 4681Likewise, the port needs to be set again when control enters 4682non-locally. 4683 4684 Scheme code can use the ‘dynamic-wind’ function to arrange for the 4685setting and resetting of the global state. C code can use the 4686corresponding ‘scm_internal_dynamic_wind’ function, or a 4687‘scm_dynwind_begin’/‘scm_dynwind_end’ pair together with suitable 4688’dynwind actions’ (*note Dynamic Wind::). 4689 4690 Instead of coping with non-local control flow, you can also prevent 4691it by erecting a _continuation barrier_, *Note Continuation Barriers::. 4692The function ‘scm_c_with_continuation_barrier’, for example, is 4693guaranteed to return exactly once. 4694 4695 4696File: guile.info, Node: Asynchronous Signals, Next: Multi-Threading, Prev: Control Flow, Up: General Libguile Concepts 4697 46985.4.4 Asynchronous Signals 4699-------------------------- 4700 4701You can not call libguile functions from handlers for POSIX signals, but 4702you can register Scheme handlers for POSIX signals such as ‘SIGINT’. 4703These handlers do not run during the actual signal delivery. Instead, 4704they are run when the program (more precisely, the thread that the 4705handler has been registered for) reaches the next _safe point_. 4706 4707 The libguile functions themselves have many such safe points. 4708Consequently, you must be prepared for arbitrary actions anytime you 4709call a libguile function. For example, even ‘scm_cons’ can contain a 4710safe point and when a signal handler is pending for your thread, calling 4711‘scm_cons’ will run this handler and anything might happen, including a 4712non-local exit although ‘scm_cons’ would not ordinarily do such a thing 4713on its own. 4714 4715 If you do not want to allow the running of asynchronous signal 4716handlers, you can block them temporarily with 4717‘scm_dynwind_block_asyncs’, for example. *Note Asyncs::. 4718 4719 Since signal handling in Guile relies on safe points, you need to 4720make sure that your functions do offer enough of them. Normally, 4721calling libguile functions in the normal course of action is all that is 4722needed. But when a thread might spent a long time in a code section 4723that calls no libguile function, it is good to include explicit safe 4724points. This can allow the user to interrupt your code with <C-c>, for 4725example. 4726 4727 You can do this with the macro ‘SCM_TICK’. This macro is 4728syntactically a statement. That is, you could use it like this: 4729 4730 while (1) 4731 { 4732 SCM_TICK; 4733 do_some_work (); 4734 } 4735 4736 Frequent execution of a safe point is even more important in multi 4737threaded programs, *Note Multi-Threading::. 4738 4739 4740File: guile.info, Node: Multi-Threading, Prev: Asynchronous Signals, Up: General Libguile Concepts 4741 47425.4.5 Multi-Threading 4743--------------------- 4744 4745Guile can be used in multi-threaded programs just as well as in 4746single-threaded ones. 4747 4748 Each thread that wants to use functions from libguile must put itself 4749into _guile mode_ and must then follow a few rules. If it doesn’t want 4750to honor these rules in certain situations, a thread can temporarily 4751leave guile mode (but can no longer use libguile functions during that 4752time, of course). 4753 4754 Threads enter guile mode by calling ‘scm_with_guile’, 4755‘scm_boot_guile’, or ‘scm_init_guile’. As explained in the reference 4756documentation for these functions, Guile will then learn about the stack 4757bounds of the thread and can protect the ‘SCM’ values that are stored in 4758local variables. When a thread puts itself into guile mode for the 4759first time, it gets a Scheme representation and is listed by 4760‘all-threads’, for example. 4761 4762 Threads in guile mode can block (e.g., do blocking I/O) without 4763causing any problems(1); temporarily leaving guile mode with 4764‘scm_without_guile’ before blocking slightly improves GC performance, 4765though. For some common blocking operations, Guile provides convenience 4766functions. For example, if you want to lock a pthread mutex while in 4767guile mode, you might want to use ‘scm_pthread_mutex_lock’ which is just 4768like ‘pthread_mutex_lock’ except that it leaves guile mode while 4769blocking. 4770 4771 All libguile functions are (intended to be) robust in the face of 4772multiple threads using them concurrently. This means that there is no 4773risk of the internal data structures of libguile becoming corrupted in 4774such a way that the process crashes. 4775 4776 A program might still produce nonsensical results, though. Taking 4777hashtables as an example, Guile guarantees that you can use them from 4778multiple threads concurrently and a hashtable will always remain a valid 4779hashtable and Guile will not crash when you access it. It does not 4780guarantee, however, that inserting into it concurrently from two threads 4781will give useful results: only one insertion might actually happen, none 4782might happen, or the table might in general be modified in a totally 4783arbitrary manner. (It will still be a valid hashtable, but not the one 4784that you might have expected.) Guile might also signal an error when it 4785detects a harmful race condition. 4786 4787 Thus, you need to put in additional synchronizations when multiple 4788threads want to use a single hashtable, or any other mutable Scheme 4789object. 4790 4791 When writing C code for use with libguile, you should try to make it 4792robust as well. An example that converts a list into a vector will help 4793to illustrate. Here is a correct version: 4794 4795 SCM 4796 my_list_to_vector (SCM list) 4797 { 4798 SCM vector = scm_make_vector (scm_length (list), SCM_UNDEFINED); 4799 size_t len, i; 4800 4801 len = scm_c_vector_length (vector); 4802 i = 0; 4803 while (i < len && scm_is_pair (list)) 4804 { 4805 scm_c_vector_set_x (vector, i, scm_car (list)); 4806 list = scm_cdr (list); 4807 i++; 4808 } 4809 4810 return vector; 4811 } 4812 4813 The first thing to note is that storing into a ‘SCM’ location 4814concurrently from multiple threads is guaranteed to be robust: you don’t 4815know which value wins but it will in any case be a valid ‘SCM’ value. 4816 4817 But there is no guarantee that the list referenced by LIST is not 4818modified in another thread while the loop iterates over it. Thus, while 4819copying its elements into the vector, the list might get longer or 4820shorter. For this reason, the loop must check both that it doesn’t 4821overrun the vector and that it doesn’t overrun the list. Otherwise, 4822‘scm_c_vector_set_x’ would raise an error if the index is out of range, 4823and ‘scm_car’ and ‘scm_cdr’ would raise an error if the value is not a 4824pair. 4825 4826 It is safe to use ‘scm_car’ and ‘scm_cdr’ on the local variable LIST 4827once it is known that the variable contains a pair. The contents of the 4828pair might change spontaneously, but it will always stay a valid pair 4829(and a local variable will of course not spontaneously point to a 4830different Scheme object). 4831 4832 Likewise, a vector such as the one returned by ‘scm_make_vector’ is 4833guaranteed to always stay the same length so that it is safe to only use 4834scm_c_vector_length once and store the result. (In the example, VECTOR 4835is safe anyway since it is a fresh object that no other thread can 4836possibly know about until it is returned from ‘my_list_to_vector’.) 4837 4838 Of course the behavior of ‘my_list_to_vector’ is suboptimal when LIST 4839does indeed get asynchronously lengthened or shortened in another 4840thread. But it is robust: it will always return a valid vector. That 4841vector might be shorter than expected, or its last elements might be 4842unspecified, but it is a valid vector and if a program wants to rule out 4843these cases, it must avoid modifying the list asynchronously. 4844 4845 Here is another version that is also correct: 4846 4847 SCM 4848 my_pedantic_list_to_vector (SCM list) 4849 { 4850 SCM vector = scm_make_vector (scm_length (list), SCM_UNDEFINED); 4851 size_t len, i; 4852 4853 len = scm_c_vector_length (vector); 4854 i = 0; 4855 while (i < len) 4856 { 4857 scm_c_vector_set_x (vector, i, scm_car (list)); 4858 list = scm_cdr (list); 4859 i++; 4860 } 4861 4862 return vector; 4863 } 4864 4865 This version relies on the error-checking behavior of ‘scm_car’ and 4866‘scm_cdr’. When the list is shortened (that is, when LIST holds a 4867non-pair), ‘scm_car’ will throw an error. This might be preferable to 4868just returning a half-initialized vector. 4869 4870 The API for accessing vectors and arrays of various kinds from C 4871takes a slightly different approach to thread-robustness. In order to 4872get at the raw memory that stores the elements of an array, you need to 4873_reserve_ that array as long as you need the raw memory. During the 4874time an array is reserved, its elements can still spontaneously change 4875their values, but the memory itself and other things like the size of 4876the array are guaranteed to stay fixed. Any operation that would change 4877these parameters of an array that is currently reserved will signal an 4878error. In order to avoid these errors, a program should of course put 4879suitable synchronization mechanisms in place. As you can see, Guile 4880itself is again only concerned about robustness, not about correctness: 4881without proper synchronization, your program will likely not be correct, 4882but the worst consequence is an error message. 4883 4884 Real thread-safety often requires that a critical section of code is 4885executed in a certain restricted manner. A common requirement is that 4886the code section is not entered a second time when it is already being 4887executed. Locking a mutex while in that section ensures that no other 4888thread will start executing it, blocking asyncs ensures that no 4889asynchronous code enters the section again from the current thread, and 4890the error checking of Guile mutexes guarantees that an error is 4891signalled when the current thread accidentally reenters the critical 4892section via recursive function calls. 4893 4894 Guile provides two mechanisms to support critical sections as 4895outlined above. You can either use the macros 4896‘SCM_CRITICAL_SECTION_START’ and ‘SCM_CRITICAL_SECTION_END’ for very 4897simple sections; or use a dynwind context together with a call to 4898‘scm_dynwind_critical_section’. 4899 4900 The macros only work reliably for critical sections that are 4901guaranteed to not cause a non-local exit. They also do not detect an 4902accidental reentry by the current thread. Thus, you should probably 4903only use them to delimit critical sections that do not contain calls to 4904libguile functions or to other external functions that might do 4905complicated things. 4906 4907 The function ‘scm_dynwind_critical_section’, on the other hand, will 4908correctly deal with non-local exits because it requires a dynwind 4909context. Also, by using a separate mutex for each critical section, it 4910can detect accidental reentries. 4911 4912 ---------- Footnotes ---------- 4913 4914 (1) In Guile 1.8, a thread blocking in guile mode would prevent 4915garbage collection to occur. Thus, threads had to leave guile mode 4916whenever they could block. This is no longer needed with Guile 2.X. 4917 4918 4919File: guile.info, Node: Defining New Foreign Object Types, Next: Function Snarfing, Prev: General Libguile Concepts, Up: Programming in C 4920 49215.5 Defining New Foreign Object Types 4922===================================== 4923 4924The “foreign object type” facility is Guile’s mechanism for importing 4925object and types from C or other languages into Guile’s system. If you 4926have a C ‘struct foo’ type, for example, you can define a corresponding 4927Guile foreign object type that allows Scheme code to handle ‘struct foo 4928*’ objects. 4929 4930 To define a new foreign object type, the programmer provides Guile 4931with some essential information about the type — what its name is, how 4932many fields it has, and its finalizer (if any) — and Guile allocates a 4933fresh type for it. Foreign objects can be accessed from Scheme or from 4934C. 4935 4936* Menu: 4937 4938* Defining Foreign Object Types:: 4939* Creating Foreign Objects:: 4940* Type Checking of Foreign Objects:: 4941* Foreign Object Memory Management:: 4942* Foreign Objects and Scheme:: 4943 4944 4945File: guile.info, Node: Defining Foreign Object Types, Next: Creating Foreign Objects, Up: Defining New Foreign Object Types 4946 49475.5.1 Defining Foreign Object Types 4948----------------------------------- 4949 4950To create a new foreign object type from C, call 4951‘scm_make_foreign_object_type’. It returns a value of type ‘SCM’ which 4952identifies the new type. 4953 4954 Here is how one might declare a new type representing eight-bit 4955gray-scale images: 4956 4957 #include <libguile.h> 4958 4959 struct image { 4960 int width, height; 4961 char *pixels; 4962 4963 /* The name of this image */ 4964 SCM name; 4965 4966 /* A function to call when this image is 4967 modified, e.g., to update the screen, 4968 or SCM_BOOL_F if no action necessary */ 4969 SCM update_func; 4970 }; 4971 4972 static SCM image_type; 4973 4974 void 4975 init_image_type (void) 4976 { 4977 SCM name, slots; 4978 scm_t_struct_finalize finalizer; 4979 4980 name = scm_from_utf8_symbol ("image"); 4981 slots = scm_list_1 (scm_from_utf8_symbol ("data")); 4982 finalizer = NULL; 4983 4984 image_type = 4985 scm_make_foreign_object_type (name, slots, finalizer); 4986 } 4987 4988 The result is an initialized ‘image_type’ value that identifies the 4989new foreign object type. The next section describes how to create 4990foreign objects and how to access their slots. 4991 4992 4993File: guile.info, Node: Creating Foreign Objects, Next: Type Checking of Foreign Objects, Prev: Defining Foreign Object Types, Up: Defining New Foreign Object Types 4994 49955.5.2 Creating Foreign Objects 4996------------------------------ 4997 4998Foreign objects contain zero or more “slots” of data. A slot can hold a 4999pointer, an integer that fits into a ‘size_t’ or ‘ssize_t’, or a ‘SCM’ 5000value. 5001 5002 All objects of a given foreign type have the same number of slots. 5003In the example from the previous section, the ‘image’ type has one slot, 5004because the slots list passed to ‘scm_make_foreign_object_type’ is of 5005length one. (The actual names given to slots are unimportant for most 5006users of the C interface, but can be used on the Scheme side to 5007introspect on the foreign object.) 5008 5009 To construct a foreign object and initialize its first slot, call 5010‘scm_make_foreign_object_1 (TYPE, FIRST_SLOT_VALUE)’. There are 5011similarly named constructors for initializing 0, 1, 2, or 3 slots, or 5012initializing N slots via an array. *Note Foreign Objects::, for full 5013details. Any fields that are not explicitly initialized are set to 0. 5014 5015 To get or set the value of a slot by index, you can use the 5016‘scm_foreign_object_ref’ and ‘scm_foreign_object_set_x’ functions. 5017These functions take and return values as ‘void *’ pointers; there are 5018corresponding convenience procedures like ‘_signed_ref’, 5019‘_unsigned_set_x’ and so on for dealing with slots as signed or unsigned 5020integers. 5021 5022 Foreign objects fields that are pointers can be tricky to manage. If 5023possible, it is best that all memory that is referenced by a foreign 5024object be managed by the garbage collector. That way, the GC can 5025automatically ensure that memory is accessible when it is needed, and 5026freed when it becomes inaccessible. If this is not the case for your 5027program – for example, if you are exposing an object to Scheme that was 5028allocated by some other, Guile-unaware part of your program – then you 5029will probably need to implement a finalizer. *Note Foreign Object 5030Memory Management::, for more. 5031 5032 Continuing the example from the previous section, if the global 5033variable ‘image_type’ contains the type returned by 5034‘scm_make_foreign_object_type’, here is how we could construct a foreign 5035object whose “data” field contains a pointer to a freshly allocated 5036‘struct image’: 5037 5038 SCM 5039 make_image (SCM name, SCM s_width, SCM s_height) 5040 { 5041 struct image *image; 5042 int width = scm_to_int (s_width); 5043 int height = scm_to_int (s_height); 5044 5045 /* Allocate the `struct image'. Because we 5046 use scm_gc_malloc, this memory block will 5047 be automatically reclaimed when it becomes 5048 inaccessible, and its members will be traced 5049 by the garbage collector. */ 5050 image = (struct image *) 5051 scm_gc_malloc (sizeof (struct image), "image"); 5052 5053 image->width = width; 5054 image->height = height; 5055 5056 /* Allocating the pixels with 5057 scm_gc_malloc_pointerless means that the 5058 pixels data is collectable by GC, but 5059 that GC shouldn't spend time tracing its 5060 contents for nested pointers because there 5061 aren't any. */ 5062 image->pixels = 5063 scm_gc_malloc_pointerless (width * height, "image pixels"); 5064 5065 image->name = name; 5066 image->update_func = SCM_BOOL_F; 5067 5068 /* Now wrap the struct image* in a new foreign 5069 object, and return that object. */ 5070 return scm_make_foreign_object_1 (image_type, image); 5071 } 5072 5073 We use ‘scm_gc_malloc_pointerless’ for the pixel buffer to tell the 5074garbage collector not to scan it for pointers. Calls to 5075‘scm_gc_malloc’, ‘scm_make_foreign_object_1’, and 5076‘scm_gc_malloc_pointerless’ raise an exception in out-of-memory 5077conditions; the garbage collector is able to reclaim previously 5078allocated memory if that happens. 5079 5080 5081File: guile.info, Node: Type Checking of Foreign Objects, Next: Foreign Object Memory Management, Prev: Creating Foreign Objects, Up: Defining New Foreign Object Types 5082 50835.5.3 Type Checking of Foreign Objects 5084-------------------------------------- 5085 5086Functions that operate on foreign objects should check that the passed 5087‘SCM’ value indeed is of the correct type before accessing its data. 5088They can do this with ‘scm_assert_foreign_object_type’. 5089 5090 For example, here is a simple function that operates on an image 5091object, and checks the type of its argument. 5092 5093 SCM 5094 clear_image (SCM image_obj) 5095 { 5096 int area; 5097 struct image *image; 5098 5099 scm_assert_foreign_object_type (image_type, image_obj); 5100 5101 image = scm_foreign_object_ref (image_obj, 0); 5102 area = image->width * image->height; 5103 memset (image->pixels, 0, area); 5104 5105 /* Invoke the image's update function. */ 5106 if (scm_is_true (image->update_func)) 5107 scm_call_0 (image->update_func); 5108 5109 return SCM_UNSPECIFIED; 5110 } 5111 5112 5113File: guile.info, Node: Foreign Object Memory Management, Next: Foreign Objects and Scheme, Prev: Type Checking of Foreign Objects, Up: Defining New Foreign Object Types 5114 51155.5.4 Foreign Object Memory Management 5116-------------------------------------- 5117 5118Once a foreign object has been released to the tender mercies of the 5119Scheme system, it must be prepared to survive garbage collection. In 5120the example above, all the memory associated with the foreign object is 5121managed by the garbage collector because we used the ‘scm_gc_’ 5122allocation functions. Thus, no special care must be taken: the garbage 5123collector automatically scans them and reclaims any unused memory. 5124 5125 However, when data associated with a foreign object is managed in 5126some other way—e.g., ‘malloc’’d memory or file descriptors—it is 5127possible to specify a “finalizer” function to release those resources 5128when the foreign object is reclaimed. 5129 5130 As discussed in *note Garbage Collection::, Guile’s garbage collector 5131will reclaim inaccessible memory as needed. This reclamation process 5132runs concurrently with the main program. When Guile analyzes the heap 5133and determines that an object’s memory can be reclaimed, that memory is 5134put on a “free list” of objects that can be reclaimed. Usually that’s 5135the end of it—the object is available for immediate re-use. However 5136some objects can have “finalizers” associated with them—functions that 5137are called on reclaimable objects to effect any external cleanup 5138actions. 5139 5140 Finalizers are tricky business and it is best to avoid them. They 5141can be invoked at unexpected times, or not at all—for example, they are 5142not invoked on process exit. They don’t help the garbage collector do 5143its job; in fact, they are a hindrance. Furthermore, they perturb the 5144garbage collector’s internal accounting. The GC decides to scan the 5145heap when it thinks that it is necessary, after some amount of 5146allocation. Finalizable objects almost always represent an amount of 5147allocation that is invisible to the garbage collector. The effect can 5148be that the actual resource usage of a system with finalizable objects 5149is higher than what the GC thinks it should be. 5150 5151 All those caveats aside, some foreign object types will need 5152finalizers. For example, if we had a foreign object type that wrapped 5153file descriptors—and we aren’t suggesting this, as Guile already has 5154ports —then you might define the type like this: 5155 5156 static SCM file_type; 5157 5158 static void 5159 finalize_file (SCM file) 5160 { 5161 int fd = scm_foreign_object_signed_ref (file, 0); 5162 if (fd >= 0) 5163 { 5164 scm_foreign_object_signed_set_x (file, 0, -1); 5165 close (fd); 5166 } 5167 } 5168 5169 static void 5170 init_file_type (void) 5171 { 5172 SCM name, slots; 5173 scm_t_struct_finalize finalizer; 5174 5175 name = scm_from_utf8_symbol ("file"); 5176 slots = scm_list_1 (scm_from_utf8_symbol ("fd")); 5177 finalizer = finalize_file; 5178 5179 image_type = 5180 scm_make_foreign_object_type (name, slots, finalizer); 5181 } 5182 5183 static SCM 5184 make_file (int fd) 5185 { 5186 return scm_make_foreign_object_1 (file_type, (void *) fd); 5187 } 5188 5189 Note that the finalizer may be invoked in ways and at times you might 5190not expect. In a Guile built without threading support, finalizers are 5191invoked via “asyncs”, which interleaves them with running Scheme code; 5192*note Asyncs::. If the user’s Guile is built with support for threads, 5193the finalizer will probably be called by a dedicated finalization 5194thread, unless the user invokes ‘scm_run_finalizers ()’ explicitly. 5195 5196 In either case, finalizers run concurrently with the main program, 5197and so they need to be async-safe and thread-safe. If for some reason 5198this is impossible, perhaps because you are embedding Guile in some 5199application that is not itself thread-safe, you have a few options. One 5200is to use guardians instead of finalizers, and arrange to pump the 5201guardians for finalizable objects. *Note Guardians::, for more 5202information. The other option is to disable automatic finalization 5203entirely, and arrange to call ‘scm_run_finalizers ()’ at appropriate 5204points. *Note Foreign Objects::, for more on these interfaces. 5205 5206 Finalizers are allowed to allocate memory, access GC-managed memory, 5207and in general can do anything any Guile user code can do. This was not 5208the case in Guile 1.8, where finalizers were much more restricted. In 5209particular, in Guile 2.0, finalizers can resuscitate objects. We do not 5210recommend that users avail themselves of this possibility, however, as a 5211resuscitated object can re-expose other finalizable objects that have 5212been already finalized back to Scheme. These objects will not be 5213finalized again, but they could cause use-after-free problems to code 5214that handles objects of that particular foreign object type. To guard 5215against this possibility, robust finalization routines should clear 5216state from the foreign object, as in the above ‘free_file’ example. 5217 5218 One final caveat. Foreign object finalizers are associated with the 5219lifetime of a foreign object, not of its fields. If you access a field 5220of a finalizable foreign object, and do not arrange to keep a reference 5221on the foreign object itself, it could be that the outer foreign object 5222gets finalized while you are working with its field. 5223 5224 For example, consider a procedure to read some data from a file, from 5225our example above. 5226 5227 SCM 5228 read_bytes (SCM file, SCM n) 5229 { 5230 int fd; 5231 SCM buf; 5232 size_t len, pos; 5233 5234 scm_assert_foreign_object_type (file_type, file); 5235 5236 fd = scm_foreign_object_signed_ref (file, 0); 5237 if (fd < 0) 5238 scm_wrong_type_arg_msg ("read-bytes", SCM_ARG1, 5239 file, "open file"); 5240 5241 len = scm_to_size_t (n); 5242 SCM buf = scm_c_make_bytevector (scm_to_size_t (n)); 5243 5244 pos = 0; 5245 while (pos < len) 5246 { 5247 char *bytes = SCM_BYTEVECTOR_CONTENTS (buf); 5248 ssize_t count = read (fd, bytes + pos, len - pos); 5249 if (count < 0) 5250 scm_syserror ("read-bytes"); 5251 if (count == 0) 5252 break; 5253 pos += count; 5254 } 5255 5256 scm_remember_upto_here_1 (file); 5257 5258 return scm_values (scm_list_2 (buf, scm_from_size_t (pos))); 5259 } 5260 5261 After the prelude, only the ‘fd’ value is used and the C compiler has 5262no reason to keep the ‘file’ object around. If ‘scm_c_make_bytevector’ 5263results in a garbage collection, ‘file’ might not be on the stack or 5264anywhere else and could be finalized, leaving ‘read’ to read a closed 5265(or, in a multi-threaded program, possibly re-used) file descriptor. 5266The use of ‘scm_remember_upto_here_1’ prevents this, by creating a 5267reference to ‘file’ after all data accesses. *Note Garbage Collection 5268Functions::. 5269 5270 ‘scm_remember_upto_here_1’ is only needed on finalizable objects, 5271because garbage collection of other values is invisible to the program – 5272it happens when needed, and is not observable. But if you can, save 5273yourself the headache and build your program in such a way that it 5274doesn’t need finalization. 5275 5276 5277File: guile.info, Node: Foreign Objects and Scheme, Prev: Foreign Object Memory Management, Up: Defining New Foreign Object Types 5278 52795.5.5 Foreign Objects and Scheme 5280-------------------------------- 5281 5282It is also possible to create foreign objects and object types from 5283Scheme, and to access fields of foreign objects from Scheme. For 5284example, the file example from the last section could be equivalently 5285expressed as: 5286 5287 (define-module (my-file) 5288 #:use-module (system foreign-object) 5289 #:use-module ((oop goops) #:select (make)) 5290 #:export (make-file)) 5291 5292 (define (finalize-file file) 5293 (let ((fd (struct-ref file 0))) 5294 (unless (< fd 0) 5295 (struct-set! file 0 -1) 5296 (close-fdes fd)))) 5297 5298 (define <file> 5299 (make-foreign-object-type '<file> '(fd) 5300 #:finalizer finalize-file)) 5301 5302 (define (make-file fd) 5303 (make <file> #:fd fd)) 5304 5305 Here we see that the result of ‘make-foreign-object-type’, which is 5306the equivalent of ‘scm_make_foreign_object_type’, is a struct vtable. 5307*Note Vtables::, for more information. To instantiate the foreign 5308object, which is really a Guile struct, we use ‘make’. (We could have 5309used ‘make-struct/no-tail’, but as an implementation detail, finalizers 5310are attached in the ‘initialize’ method called by ‘make’). To access 5311the fields, we use ‘struct-ref’ and ‘struct-set!’. *Note Structure 5312Basics::. 5313 5314 There is a convenience syntax, ‘define-foreign-object-type’, that 5315defines a type along with a constructor, and getters for the fields. An 5316appropriate invocation of ‘define-foreign-object-type’ for the file 5317object type could look like this: 5318 5319 (use-modules (system foreign-object)) 5320 5321 (define-foreign-object-type <file> 5322 make-file 5323 (fd) 5324 #:finalizer finalize-file) 5325 5326 This defines the ‘<file>’ type with one field, a ‘make-file’ 5327constructor, and a getter for the ‘fd’ field, bound to ‘fd’. 5328 5329 Foreign object types are not only vtables but are actually GOOPS 5330classes, as hinted at above. *Note GOOPS::, for more on Guile’s 5331object-oriented programming system. Thus one can define print and 5332equality methods using GOOPS: 5333 5334 (use-modules (oop goops)) 5335 5336 (define-method (write (file <file>) port) 5337 ;; Assuming existence of the `fd' getter 5338 (format port "#<<file> ~a>" (fd file))) 5339 5340 (define-method (equal? (a <file>) (b <file>)) 5341 (eqv? (fd a) (fd b))) 5342 5343 One can even sub-class foreign types. 5344 5345 (define-class <named-file> (<file>) 5346 (name #:init-keyword #:name #:init-value #f #:accessor name)) 5347 5348 The question arises of how to construct these values, given that 5349‘make-file’ returns a plain old ‘<file>’ object. It turns out that you 5350can use the GOOPS construction interface, where every field of the 5351foreign object has an associated initialization keyword argument. 5352 5353 (define* (my-open-file name #:optional (flags O_RDONLY)) 5354 (make <named-file> #:fd (open-fdes name flags) #:name name)) 5355 5356 (define-method (write (file <named-file>) port) 5357 (format port "#<<file> ~s ~a>" (name file) (fd file))) 5358 5359 *Note Foreign Objects::, for full documentation on the Scheme 5360interface to foreign objects. *Note GOOPS::, for more on GOOPS. 5361 5362 As a final note, you might wonder how this system supports 5363encapsulation of sensitive values. First, we have to recognize that 5364some facilities are essentially unsafe and have global scope. For 5365example, in C, the integrity and confidentiality of a part of a program 5366is at the mercy of every other part of that program – because any part 5367of the program can read and write anything in its address space. At the 5368same time, principled access to structured data is organized in C on 5369lexical boundaries; if you don’t expose accessors for your object, you 5370trust other parts of the program not to work around that barrier. 5371 5372 The situation is not dissimilar in Scheme. Although Scheme’s unsafe 5373constructs are fewer in number than in C, they do exist. The ‘(system 5374foreign)’ module can be used to violate confidentiality and integrity, 5375and shouldn’t be exposed to untrusted code. Although ‘struct-ref’ and 5376‘struct-set!’ are less unsafe, they still have a cross-cutting 5377capability of drilling through abstractions. Performing a ‘struct-set!’ 5378on a foreign object slot could cause unsafe foreign code to crash. 5379Ultimately, structures in Scheme are capabilities for abstraction, and 5380not abstractions themselves. 5381 5382 That leaves us with the lexical capabilities, like constructors and 5383accessors. Here is where encapsulation lies: the practical degree to 5384which the innards of your foreign objects are exposed is the degree to 5385which their accessors are lexically available in user code. If you want 5386to allow users to reference fields of your foreign object, provide them 5387with a getter. Otherwise you should assume that the only access to your 5388object may come from your code, which has the relevant authority, or via 5389code with access to cross-cutting ‘struct-ref’ and such, which also has 5390the cross-cutting authority. 5391 5392 5393File: guile.info, Node: Function Snarfing, Next: Programming Overview, Prev: Defining New Foreign Object Types, Up: Programming in C 5394 53955.6 Function Snarfing 5396===================== 5397 5398When writing C code for use with Guile, you typically define a set of C 5399functions, and then make some of them visible to the Scheme world by 5400calling ‘scm_c_define_gsubr’ or related functions. If you have many 5401functions to publish, it can sometimes be annoying to keep the list of 5402calls to ‘scm_c_define_gsubr’ in sync with the list of function 5403definitions. 5404 5405 Guile provides the ‘guile-snarf’ program to manage this problem. 5406Using this tool, you can keep all the information needed to define the 5407function alongside the function definition itself; ‘guile-snarf’ will 5408extract this information from your source code, and automatically 5409generate a file of calls to ‘scm_c_define_gsubr’ which you can 5410‘#include’ into an initialization function. 5411 5412 The snarfing mechanism works for many kind of initialization actions, 5413not just for collecting calls to ‘scm_c_define_gsubr’. For a full list 5414of what can be done, *Note Snarfing Macros::. 5415 5416 The ‘guile-snarf’ program is invoked like this: 5417 5418 guile-snarf [-o OUTFILE] [CPP-ARGS ...] 5419 5420 This command will extract initialization actions to OUTFILE. When no 5421OUTFILE has been specified or when OUTFILE is ‘-’, standard output will 5422be used. The C preprocessor is called with CPP-ARGS (which usually 5423include an input file) and the output is filtered to extract the 5424initialization actions. 5425 5426 If there are errors during processing, OUTFILE is deleted and the 5427program exits with non-zero status. 5428 5429 During snarfing, the pre-processor macro ‘SCM_MAGIC_SNARFER’ is 5430defined. You could use this to avoid including snarfer output files 5431that don’t yet exist by writing code like this: 5432 5433 #ifndef SCM_MAGIC_SNARFER 5434 #include "foo.x" 5435 #endif 5436 5437 Here is how you might define the Scheme function ‘clear-image’, 5438implemented by the C function ‘clear_image’: 5439 5440 #include <libguile.h> 5441 5442 SCM_DEFINE (clear_image, "clear-image", 1, 0, 0, 5443 (SCM image), 5444 "Clear the image.") 5445 { 5446 /* C code to clear the image in image... */ 5447 } 5448 5449 void 5450 init_image_type () 5451 { 5452 #include "image-type.x" 5453 } 5454 5455 The ‘SCM_DEFINE’ declaration says that the C function ‘clear_image’ 5456implements a Scheme function called ‘clear-image’, which takes one 5457required argument (of type ‘SCM’ and named ‘image’), no optional 5458arguments, and no rest argument. The string ‘"Clear the image."’ 5459provides a short help text for the function, it is called a “docstring”. 5460 5461 ‘SCM_DEFINE’ macro also defines a static array of characters 5462initialized to the Scheme name of the function. In this case, 5463‘s_clear_image’ is set to the C string, "clear-image". You might want 5464to use this symbol when generating error messages. 5465 5466 Assuming the text above lives in a file named ‘image-type.c’, you 5467will need to execute the following command to prepare this file for 5468compilation: 5469 5470 guile-snarf -o image-type.x image-type.c 5471 5472 This scans ‘image-type.c’ for ‘SCM_DEFINE’ declarations, and writes 5473to ‘image-type.x’ the output: 5474 5475 scm_c_define_gsubr ("clear-image", 1, 0, 0, (SCM (*)() ) clear_image); 5476 5477 When compiled normally, ‘SCM_DEFINE’ is a macro which expands to the 5478function header for ‘clear_image’. 5479 5480 Note that the output file name matches the ‘#include’ from the input 5481file. Also, you still need to provide all the same information you 5482would if you were using ‘scm_c_define_gsubr’ yourself, but you can place 5483the information near the function definition itself, so it is less 5484likely to become incorrect or out-of-date. 5485 5486 If you have many files that ‘guile-snarf’ must process, you should 5487consider using a fragment like the following in your Makefile: 5488 5489 snarfcppopts = $(DEFS) $(INCLUDES) $(CPPFLAGS) $(CFLAGS) 5490 .SUFFIXES: .x 5491 .c.x: 5492 guile-snarf -o $@ $< $(snarfcppopts) 5493 5494 This tells make to run ‘guile-snarf’ to produce each needed ‘.x’ file 5495from the corresponding ‘.c’ file. 5496 5497 The program ‘guile-snarf’ passes its command-line arguments directly 5498to the C preprocessor, which it uses to extract the information it needs 5499from the source code. this means you can pass normal compilation flags 5500to ‘guile-snarf’ to define preprocessor symbols, add header file 5501directories, and so on. 5502 5503 5504File: guile.info, Node: Programming Overview, Next: Autoconf Support, Prev: Function Snarfing, Up: Programming in C 5505 55065.7 An Overview of Guile Programming 5507==================================== 5508 5509Guile is designed as an extension language interpreter that is 5510straightforward to integrate with applications written in C (and C++). 5511The big win here for the application developer is that Guile 5512integration, as the Guile web page says, “lowers your project’s 5513hacktivation energy.” Lowering the hacktivation energy means that you, 5514as the application developer, _and your users_, reap the benefits that 5515flow from being able to extend the application in a high level extension 5516language rather than in plain old C. 5517 5518 In abstract terms, it’s difficult to explain what this really means 5519and what the integration process involves, so instead let’s begin by 5520jumping straight into an example of how you might integrate Guile into 5521an existing program, and what you could expect to gain by so doing. 5522With that example under our belts, we’ll then return to a more general 5523analysis of the arguments involved and the range of programming options 5524available. 5525 5526* Menu: 5527 5528* Extending Dia:: How one might extend Dia using Guile. 5529* Scheme vs C:: Why Scheme is more hackable than C. 5530* Testbed Example:: Example: using Guile in a testbed. 5531* Programming Options:: Options for Guile programming. 5532* User Programming:: How about application users? 5533 5534 5535File: guile.info, Node: Extending Dia, Next: Scheme vs C, Up: Programming Overview 5536 55375.7.1 How One Might Extend Dia Using Guile 5538------------------------------------------ 5539 5540Dia is a free software program for drawing schematic diagrams like flow 5541charts and floor plans (<http://www.gnome.org/projects/dia/>). This 5542section conducts the thought experiment of adding Guile to Dia. In so 5543doing, it aims to illustrate several of the steps and considerations 5544involved in adding Guile to applications in general. 5545 5546* Menu: 5547 5548* Dia Objective:: Deciding why you want to add Guile. 5549* Dia Steps:: Four steps required to add Guile. 5550* Dia Objects:: How to represent Dia data in Scheme. 5551* Dia Primitives:: Writing Guile primitives for Dia. 5552* Dia Hook:: Providing a hook for Scheme evaluation. 5553* Dia Structure:: Overall structure for adding Guile. 5554* Dia Advanced:: Going further with Dia and Guile. 5555 5556 5557File: guile.info, Node: Dia Objective, Next: Dia Steps, Up: Extending Dia 5558 55595.7.1.1 Deciding Why You Want to Add Guile 5560.......................................... 5561 5562First off, you should understand why you want to add Guile to Dia at 5563all, and that means forming a picture of what Dia does and how it does 5564it. So, what are the constituents of the Dia application? 5565 5566 • Most importantly, the “application domain objects” — in other 5567 words, the concepts that differentiate Dia from another application 5568 such as a word processor or spreadsheet: shapes, templates, 5569 connectors, pages, plus the properties of all these things. 5570 5571 • The code that manages the graphical face of the application, 5572 including the layout and display of the objects above. 5573 5574 • The code that handles input events, which indicate that the 5575 application user is wanting to do something. 5576 5577(In other words, a textbook example of the “model - view - controller” 5578paradigm.) 5579 5580 Next question: how will Dia benefit once the Guile integration is 5581complete? Several (positive!) answers are possible here, and the 5582choice is obviously up to the application developers. Still, one answer 5583is that the main benefit will be the ability to manipulate Dia’s 5584application domain objects from Scheme. 5585 5586 Suppose that Dia made a set of procedures available in Scheme, 5587representing the most basic operations on objects such as shapes, 5588connectors, and so on. Using Scheme, the application user could then 5589write code that builds upon these basic operations to create more 5590complex procedures. For example, given basic procedures to enumerate 5591the objects on a page, to determine whether an object is a square, and 5592to change the fill pattern of a single shape, the user can write a 5593Scheme procedure to change the fill pattern of all squares on the 5594current page: 5595 5596 (define (change-squares'-fill-pattern new-pattern) 5597 (for-each-shape current-page 5598 (lambda (shape) 5599 (if (square? shape) 5600 (change-fill-pattern shape new-pattern))))) 5601 5602 5603File: guile.info, Node: Dia Steps, Next: Dia Objects, Prev: Dia Objective, Up: Extending Dia 5604 56055.7.1.2 Four Steps Required to Add Guile 5606........................................ 5607 5608Assuming this objective, four steps are needed to achieve it. 5609 5610 First, you need a way of representing your application-specific 5611objects — such as ‘shape’ in the previous example — when they are passed 5612into the Scheme world. Unless your objects are so simple that they map 5613naturally into builtin Scheme data types like numbers and strings, you 5614will probably want to use Guile’s “foreign object” interface to create a 5615new Scheme data type for your objects. 5616 5617 Second, you need to write code for the basic operations like 5618‘for-each-shape’ and ‘square?’ such that they access and manipulate your 5619existing data structures correctly, and then make these operations 5620available as “primitives” on the Scheme level. 5621 5622 Third, you need to provide some mechanism within the Dia application 5623that a user can hook into to cause arbitrary Scheme code to be 5624evaluated. 5625 5626 Finally, you need to restructure your top-level application C code a 5627little so that it initializes the Guile interpreter correctly and 5628declares your “foreign objects” and “primitives” to the Scheme world. 5629 5630 The following subsections expand on these four points in turn. 5631 5632 5633File: guile.info, Node: Dia Objects, Next: Dia Primitives, Prev: Dia Steps, Up: Extending Dia 5634 56355.7.1.3 How to Represent Dia Data in Scheme 5636........................................... 5637 5638For all but the most trivial applications, you will probably want to 5639allow some representation of your domain objects to exist on the Scheme 5640level. This is where foreign objects come in, and with them issues of 5641lifetime management and garbage collection. 5642 5643 To get more concrete about this, let’s look again at the example we 5644gave earlier of how application users can use Guile to build 5645higher-level functions from the primitives that Dia itself provides. 5646 5647 (define (change-squares'-fill-pattern new-pattern) 5648 (for-each-shape current-page 5649 (lambda (shape) 5650 (if (square? shape) 5651 (change-fill-pattern shape new-pattern))))) 5652 5653 Consider what is stored here in the variable ‘shape’. For each shape 5654on the current page, the ‘for-each-shape’ primitive calls ‘(lambda 5655(shape) ...)’ with an argument representing that shape. Question is: 5656how is that argument represented on the Scheme level? The issues are as 5657follows. 5658 5659 • Whatever the representation, it has to be decodable again by the C 5660 code for the ‘square?’ and ‘change-fill-pattern’ primitives. In 5661 other words, a primitive like ‘square?’ has somehow to be able to 5662 turn the value that it receives back into something that points to 5663 the underlying C structure describing a shape. 5664 5665 • The representation must also cope with Scheme code holding on to 5666 the value for later use. What happens if the Scheme code stores 5667 ‘shape’ in a global variable, but then that shape is deleted (in a 5668 way that the Scheme code is not aware of), and later on some other 5669 Scheme code uses that global variable again in a call to, say, 5670 ‘square?’? 5671 5672 • The lifetime and memory allocation of objects that exist _only_ in 5673 the Scheme world is managed automatically by Guile’s garbage 5674 collector using one simple rule: when there are no remaining 5675 references to an object, the object is considered dead and so its 5676 memory is freed. But for objects that exist in both C and Scheme, 5677 the picture is more complicated; in the case of Dia, where the 5678 ‘shape’ argument passes transiently in and out of the Scheme world, 5679 it would be quite wrong the *delete* the underlying C shape just 5680 because the Scheme code has finished evaluation. How do we avoid 5681 this happening? 5682 5683 One resolution of these issues is for the Scheme-level representation 5684of a shape to be a new, Scheme-specific C structure wrapped up as a 5685foreign object. The foreign object is what is passed into and out of 5686Scheme code, and the Scheme-specific C structure inside the foreign 5687object points to Dia’s underlying C structure so that the code for 5688primitives like ‘square?’ can get at it. 5689 5690 To cope with an underlying shape being deleted while Scheme code is 5691still holding onto a Scheme shape value, the underlying C structure 5692should have a new field that points to the Scheme-specific foreign 5693object. When a shape is deleted, the relevant code chains through to 5694the Scheme-specific structure and sets its pointer back to the 5695underlying structure to NULL. Thus the foreign object value for the 5696shape continues to exist, but any primitive code that tries to use it 5697will detect that the underlying shape has been deleted because the 5698underlying structure pointer is NULL. 5699 5700 So, to summarize the steps involved in this resolution of the problem 5701(and assuming that the underlying C structure for a shape is ‘struct 5702dia_shape’): 5703 5704 • Define a new Scheme-specific structure that _points_ to the 5705 underlying C structure: 5706 5707 struct dia_guile_shape 5708 { 5709 struct dia_shape * c_shape; /* NULL => deleted */ 5710 } 5711 5712 • Add a field to ‘struct dia_shape’ that points to its ‘struct 5713 dia_guile_shape’ if it has one — 5714 5715 struct dia_shape 5716 { 5717 ... 5718 struct dia_guile_shape * guile_shape; 5719 } 5720 5721 — so that C code can set ‘guile_shape->c_shape’ to NULL when the 5722 underlying shape is deleted. 5723 5724 • Wrap ‘struct dia_guile_shape’ as a foreign object type. 5725 5726 • Whenever you need to represent a C shape onto the Scheme level, 5727 create a foreign object instance for it, and pass that. 5728 5729 • In primitive code that receives a shape foreign object instance, 5730 check the ‘c_shape’ field when decoding it, to find out whether the 5731 underlying C shape is still there. 5732 5733 As far as memory management is concerned, the foreign object values 5734and their Scheme-specific structures are under the control of the 5735garbage collector, whereas the underlying C structures are explicitly 5736managed in exactly the same way that Dia managed them before we thought 5737of adding Guile. 5738 5739 When the garbage collector decides to free a shape foreign object 5740value, it calls the “finalizer” function that was specified when 5741defining the shape foreign object type. To maintain the correctness of 5742the ‘guile_shape’ field in the underlying C structure, this function 5743should chain through to the underlying C structure (if it still exists) 5744and set its ‘guile_shape’ field to NULL. 5745 5746 For full documentation on defining and using foreign object types, 5747see *note Defining New Foreign Object Types::. 5748 5749 5750File: guile.info, Node: Dia Primitives, Next: Dia Hook, Prev: Dia Objects, Up: Extending Dia 5751 57525.7.1.4 Writing Guile Primitives for Dia 5753........................................ 5754 5755Once the details of object representation are decided, writing the 5756primitive function code that you need is usually straightforward. 5757 5758 A primitive is simply a C function whose arguments and return value 5759are all of type ‘SCM’, and whose body does whatever you want it to do. 5760As an example, here is a possible implementation of the ‘square?’ 5761primitive: 5762 5763 static SCM square_p (SCM shape) 5764 { 5765 struct dia_guile_shape * guile_shape; 5766 5767 /* Check that arg is really a shape object. */ 5768 scm_assert_foreign_object_type (shape_type, shape); 5769 5770 /* Access Scheme-specific shape structure. */ 5771 guile_shape = scm_foreign_object_ref (shape, 0); 5772 5773 /* Find out if underlying shape exists and is a 5774 square; return answer as a Scheme boolean. */ 5775 return scm_from_bool (guile_shape->c_shape && 5776 (guile_shape->c_shape->type == DIA_SQUARE)); 5777 } 5778 5779 Notice how easy it is to chain through from the ‘SCM shape’ parameter 5780that ‘square_p’ receives — which is a foreign object — to the 5781Scheme-specific structure inside the foreign object, and thence to the 5782underlying C structure for the shape. 5783 5784 In this code, ‘scm_assert_foreign_object_type’, 5785‘scm_foreign_object_ref’, and ‘scm_from_bool’ are from the standard 5786Guile API. We assume that ‘shape_type’ was given to us when we made the 5787shape foreign object type, using ‘scm_make_foreign_object_type’. The 5788call to ‘scm_assert_foreign_object_type’ ensures that SHAPE is indeed a 5789shape. This is needed to guard against Scheme code using the ‘square?’ 5790procedure incorrectly, as in ‘(square? "hello")’; Scheme’s latent typing 5791means that usage errors like this must be caught at run time. 5792 5793 Having written the C code for your primitives, you need to make them 5794available as Scheme procedures by calling the ‘scm_c_define_gsubr’ 5795function. ‘scm_c_define_gsubr’ (*note Primitive Procedures::) takes 5796arguments that specify the Scheme-level name for the primitive and how 5797many required, optional and rest arguments it can accept. The ‘square?’ 5798primitive always requires exactly one argument, so the call to make it 5799available in Scheme reads like this: 5800 5801 scm_c_define_gsubr ("square?", 1, 0, 0, square_p); 5802 5803 For where to put this call, see the subsection after next on the 5804structure of Guile-enabled code (*note Dia Structure::). 5805 5806 5807File: guile.info, Node: Dia Hook, Next: Dia Structure, Prev: Dia Primitives, Up: Extending Dia 5808 58095.7.1.5 Providing a Hook for the Evaluation of Scheme Code 5810.......................................................... 5811 5812To make the Guile integration useful, you have to design some kind of 5813hook into your application that application users can use to cause their 5814Scheme code to be evaluated. 5815 5816 Technically, this is straightforward; you just have to decide on a 5817mechanism that is appropriate for your application. Think of Emacs, for 5818example: when you type ‘<ESC> :’, you get a prompt where you can type in 5819any Elisp code, which Emacs will then evaluate. Or, again like Emacs, 5820you could provide a mechanism (such as an init file) to allow Scheme 5821code to be associated with a particular key sequence, and evaluate the 5822code when that key sequence is entered. 5823 5824 In either case, once you have the Scheme code that you want to 5825evaluate, as a null terminated string, you can tell Guile to evaluate it 5826by calling the ‘scm_c_eval_string’ function. 5827 5828 5829File: guile.info, Node: Dia Structure, Next: Dia Advanced, Prev: Dia Hook, Up: Extending Dia 5830 58315.7.1.6 Top-level Structure of Guile-enabled Dia 5832................................................ 5833 5834Let’s assume that the pre-Guile Dia code looks structurally like this: 5835 5836 • ‘main ()’ 5837 5838 • do lots of initialization and setup stuff 5839 • enter Gtk main loop 5840 5841 When you add Guile to a program, one (rather technical) requirement 5842is that Guile’s garbage collector needs to know where the bottom of the 5843C stack is. The easiest way to ensure this is to use ‘scm_boot_guile’ 5844like this: 5845 5846 • ‘main ()’ 5847 5848 • do lots of initialization and setup stuff 5849 • ‘scm_boot_guile (argc, argv, inner_main, NULL)’ 5850 5851 • ‘inner_main ()’ 5852 5853 • define all foreign object types 5854 • export primitives to Scheme using ‘scm_c_define_gsubr’ 5855 • enter Gtk main loop 5856 5857 In other words, you move the guts of what was previously in your 5858‘main’ function into a new function called ‘inner_main’, and then add a 5859‘scm_boot_guile’ call, with ‘inner_main’ as a parameter, to the end of 5860‘main’. 5861 5862 Assuming that you are using foreign objects and have written 5863primitive code as described in the preceding subsections, you also need 5864to insert calls to declare your new foreign objects and export the 5865primitives to Scheme. These declarations must happen _inside_ the 5866dynamic scope of the ‘scm_boot_guile’ call, but also _before_ any code 5867is run that could possibly use them — the beginning of ‘inner_main’ is 5868an ideal place for this. 5869 5870 5871File: guile.info, Node: Dia Advanced, Prev: Dia Structure, Up: Extending Dia 5872 58735.7.1.7 Going Further with Dia and Guile 5874........................................ 5875 5876The steps described so far implement an initial Guile integration that 5877already gives a lot of additional power to Dia application users. But 5878there are further steps that you could take, and it’s interesting to 5879consider a few of these. 5880 5881 In general, you could progressively move more of Dia’s source code 5882from C into Scheme. This might make the code more maintainable and 5883extensible, and it could open the door to new programming paradigms that 5884are tricky to effect in C but straightforward in Scheme. 5885 5886 A specific example of this is that you could use the guile-gtk 5887package, which provides Scheme-level procedures for most of the Gtk+ 5888library, to move the code that lays out and displays Dia objects from C 5889to Scheme. 5890 5891 As you follow this path, it naturally becomes less useful to maintain 5892a distinction between Dia’s original non-Guile-related source code, and 5893its later code implementing foreign objects and primitives for the 5894Scheme world. 5895 5896 For example, suppose that the original source code had a 5897‘dia_change_fill_pattern’ function: 5898 5899 void dia_change_fill_pattern (struct dia_shape * shape, 5900 struct dia_pattern * pattern) 5901 { 5902 /* real pattern change work */ 5903 } 5904 5905 During initial Guile integration, you add a ‘change_fill_pattern’ 5906primitive for Scheme purposes, which accesses the underlying structures 5907from its foreign object values and uses ‘dia_change_fill_pattern’ to do 5908the real work: 5909 5910 SCM change_fill_pattern (SCM shape, SCM pattern) 5911 { 5912 struct dia_shape * d_shape; 5913 struct dia_pattern * d_pattern; 5914 5915 ... 5916 5917 dia_change_fill_pattern (d_shape, d_pattern); 5918 5919 return SCM_UNSPECIFIED; 5920 } 5921 5922 At this point, it makes sense to keep ‘dia_change_fill_pattern’ and 5923‘change_fill_pattern’ separate, because ‘dia_change_fill_pattern’ can 5924also be called without going through Scheme at all, say because the user 5925clicks a button which causes a C-registered Gtk+ callback to be called. 5926 5927 But, if the code for creating buttons and registering their callbacks 5928is moved into Scheme (using guile-gtk), it may become true that 5929‘dia_change_fill_pattern’ can no longer be called other than through 5930Scheme. In which case, it makes sense to abolish it and move its 5931contents directly into ‘change_fill_pattern’, like this: 5932 5933 SCM change_fill_pattern (SCM shape, SCM pattern) 5934 { 5935 struct dia_shape * d_shape; 5936 struct dia_pattern * d_pattern; 5937 5938 ... 5939 5940 /* real pattern change work */ 5941 5942 return SCM_UNSPECIFIED; 5943 } 5944 5945 So further Guile integration progressively _reduces_ the amount of 5946functional C code that you have to maintain over the long term. 5947 5948 A similar argument applies to data representation. In the discussion 5949of foreign objects earlier, issues arose because of the different memory 5950management and lifetime models that normally apply to data structures in 5951C and in Scheme. However, with further Guile integration, you can 5952resolve this issue in a more radical way by allowing all your data 5953structures to be under the control of the garbage collector, and kept 5954alive by references from the Scheme world. Instead of maintaining an 5955array or linked list of shapes in C, you would instead maintain a list 5956in Scheme. 5957 5958 Rather like the coalescing of ‘dia_change_fill_pattern’ and 5959‘change_fill_pattern’, the practical upshot of such a change is that you 5960would no longer have to keep the ‘dia_shape’ and ‘dia_guile_shape’ 5961structures separate, and so wouldn’t need to worry about the pointers 5962between them. Instead, you could change the foreign object definition 5963to wrap the ‘dia_shape’ structure directly, and send ‘dia_guile_shape’ 5964off to the scrap yard. Cut out the middle man! 5965 5966 Finally, we come to the holy grail of Guile’s free software / 5967extension language approach. Once you have a Scheme representation for 5968interesting Dia data types like shapes, and a handy bunch of primitives 5969for manipulating them, it suddenly becomes clear that you have a bundle 5970of functionality that could have far-ranging use beyond Dia itself. In 5971other words, the data types and primitives could now become a library, 5972and Dia becomes just one of the many possible applications using that 5973library — albeit, at this early stage, a rather important one! 5974 5975 In this model, Guile becomes just the glue that binds everything 5976together. Imagine an application that usefully combined functionality 5977from Dia, Gnumeric and GnuCash — it’s tricky right now, because no such 5978application yet exists; but it’ll happen some day ... 5979 5980 5981File: guile.info, Node: Scheme vs C, Next: Testbed Example, Prev: Extending Dia, Up: Programming Overview 5982 59835.7.2 Why Scheme is More Hackable Than C 5984---------------------------------------- 5985 5986Underlying Guile’s value proposition is the assumption that programming 5987in a high level language, specifically Guile’s implementation of Scheme, 5988is necessarily better in some way than programming in C. What do we mean 5989by this claim, and how can we be so sure? 5990 5991 One class of advantages applies not only to Scheme, but more 5992generally to any interpretable, high level, scripting language, such as 5993Emacs Lisp, Python, Ruby, or TeX’s macro language. Common features of 5994all such languages, when compared to C, are that: 5995 5996 • They lend themselves to rapid and experimental development cycles, 5997 owing usually to a combination of their interpretability and the 5998 integrated development environment in which they are used. 5999 6000 • They free developers from some of the low level bookkeeping tasks 6001 associated with C programming, notably memory management. 6002 6003 • They provide high level features such as container objects and 6004 exception handling that make common programming tasks easier. 6005 6006 In the case of Scheme, particular features that make programming 6007easier — and more fun! — are its powerful mechanisms for abstracting 6008parts of programs (closures — *note About Closure::) and for iteration 6009(*note while do::). 6010 6011 The evidence in support of this argument is empirical: the huge 6012amount of code that has been written in extension languages for 6013applications that support this mechanism. Most notable are extensions 6014written in Emacs Lisp for GNU Emacs, in TeX’s macro language for TeX, 6015and in Script-Fu for the Gimp, but there is increasingly now a 6016significant code eco-system for Guile-based applications as well, such 6017as Lilypond and GnuCash. It is close to inconceivable that similar 6018amounts of functionality could have been added to these applications 6019just by writing new code in their base implementation languages. 6020 6021 6022File: guile.info, Node: Testbed Example, Next: Programming Options, Prev: Scheme vs C, Up: Programming Overview 6023 60245.7.3 Example: Using Guile for an Application Testbed 6025----------------------------------------------------- 6026 6027As an example of what this means in practice, imagine writing a testbed 6028for an application that is tested by submitting various requests (via a 6029C interface) and validating the output received. Suppose further that 6030the application keeps an idea of its current state, and that the 6031“correct” output for a given request may depend on the current 6032application state. A complete “white box”(1) test plan for this 6033application would aim to submit all possible requests in each 6034distinguishable state, and validate the output for all request/state 6035combinations. 6036 6037 To write all this test code in C would be very tedious. Suppose 6038instead that the testbed code adds a single new C function, to submit an 6039arbitrary request and return the response, and then uses Guile to export 6040this function as a Scheme procedure. The rest of the testbed can then 6041be written in Scheme, and so benefits from all the advantages of 6042programming in Scheme that were described in the previous section. 6043 6044 (In this particular example, there is an additional benefit of 6045writing most of the testbed in Scheme. A common problem for white box 6046testing is that mistakes and mistaken assumptions in the application 6047under test can easily be reproduced in the testbed code. It is more 6048difficult to copy mistakes like this when the testbed is written in a 6049different language from the application.) 6050 6051 ---------- Footnotes ---------- 6052 6053 (1) A “white box” test plan is one that incorporates knowledge of the 6054internal design of the application under test. 6055 6056 6057File: guile.info, Node: Programming Options, Next: User Programming, Prev: Testbed Example, Up: Programming Overview 6058 60595.7.4 A Choice of Programming Options 6060------------------------------------- 6061 6062The preceding arguments and example point to a model of Guile 6063programming that is applicable in many cases. According to this model, 6064Guile programming involves a balance between C and Scheme programming, 6065with the aim being to extract the greatest possible Scheme level benefit 6066from the least amount of C level work. 6067 6068 The C level work required in this model usually consists of packaging 6069and exporting functions and application objects such that they can be 6070seen and manipulated on the Scheme level. To help with this, Guile’s C 6071language interface includes utility features that aim to make this kind 6072of integration very easy for the application developer. These features 6073are documented later in this part of the manual: see REFFIXME. 6074 6075 This model, though, is really just one of a range of possible 6076programming options. If all of the functionality that you need is 6077available from Scheme, you could choose instead to write your whole 6078application in Scheme (or one of the other high level languages that 6079Guile supports through translation), and simply use Guile as an 6080interpreter for Scheme. (In the future, we hope that Guile will also be 6081able to compile Scheme code, so lessening the performance gap between C 6082and Scheme code.) Or, at the other end of the C–Scheme scale, you could 6083write the majority of your application in C, and only call out to Guile 6084occasionally for specific actions such as reading a configuration file 6085or executing a user-specified extension. The choices boil down to two 6086basic questions: 6087 6088 • Which parts of the application do you write in C, and which in 6089 Scheme (or another high level translated language)? 6090 6091 • How do you design the interface between the C and Scheme parts of 6092 your application? 6093 6094 These are of course design questions, and the right design for any 6095given application will always depend upon the particular requirements 6096that you are trying to meet. In the context of Guile, however, there 6097are some generally applicable considerations that can help you when 6098designing your answers. 6099 6100* Menu: 6101 6102* Available Functionality:: What functionality is already available? 6103* Basic Constraints:: Functional and performance constraints. 6104* Style Choices:: Your preferred programming style. 6105* Program Control:: What controls program execution? 6106 6107 6108File: guile.info, Node: Available Functionality, Next: Basic Constraints, Up: Programming Options 6109 61105.7.4.1 What Functionality is Already Available? 6111................................................ 6112 6113Suppose, for the sake of argument, that you would prefer to write your 6114whole application in Scheme. Then the API available to you consists of: 6115 6116 • standard Scheme 6117 6118 • plus the extensions to standard Scheme provided by Guile in its 6119 core distribution 6120 6121 • plus any additional functionality that you or others have packaged 6122 so that it can be loaded as a Guile Scheme module. 6123 6124 A module in the last category can either be a pure Scheme module — in 6125other words a collection of utility procedures coded in Scheme — or a 6126module that provides a Scheme interface to an extension library coded in 6127C — in other words a nice package where someone else has done the work 6128of wrapping up some useful C code for you. The set of available modules 6129is growing quickly and already includes such useful examples as ‘(gtk 6130gtk)’, which makes Gtk+ drawing functions available in Scheme, and 6131‘(database postgres)’, which provides SQL access to a Postgres database. 6132 6133 Given the growing collection of pre-existing modules, it is quite 6134feasible that your application could be implemented by combining a 6135selection of these modules together with new application code written in 6136Scheme. 6137 6138 If this approach is not enough, because the functionality that your 6139application needs is not already available in this form, and it is 6140impossible to write the new functionality in Scheme, you will need to 6141write some C code. If the required function is already available in C 6142(e.g. in a library), all you need is a little glue to connect it to the 6143world of Guile. If not, you need both to write the basic code and to 6144plumb it into Guile. 6145 6146 In either case, two general considerations are important. Firstly, 6147what is the interface by which the functionality is presented to the 6148Scheme world? Does the interface consist only of function calls (for 6149example, a simple drawing interface), or does it need to include 6150“objects” of some kind that can be passed between C and Scheme and 6151manipulated by both worlds. Secondly, how does the lifetime and memory 6152management of objects in the C code relate to the garbage collection 6153governed approach of Scheme objects? In the case where the basic C code 6154is not already written, most of the difficulties of memory management 6155can be avoided by using Guile’s C interface features from the start. 6156 6157 For the full documentation on writing C code for Guile and connecting 6158existing C code to the Guile world, see REFFIXME. 6159 6160 6161File: guile.info, Node: Basic Constraints, Next: Style Choices, Prev: Available Functionality, Up: Programming Options 6162 61635.7.4.2 Functional and Performance Constraints 6164.............................................. 6165 6166 6167File: guile.info, Node: Style Choices, Next: Program Control, Prev: Basic Constraints, Up: Programming Options 6168 61695.7.4.3 Your Preferred Programming Style 6170........................................ 6171 6172 6173File: guile.info, Node: Program Control, Prev: Style Choices, Up: Programming Options 6174 61755.7.4.4 What Controls Program Execution? 6176........................................ 6177 6178 6179File: guile.info, Node: User Programming, Prev: Programming Options, Up: Programming Overview 6180 61815.7.5 How About Application Users? 6182---------------------------------- 6183 6184So far we have considered what Guile programming means for an 6185application developer. But what if you are instead _using_ an existing 6186Guile-based application, and want to know what your options are for 6187programming and extending this application? 6188 6189 The answer to this question varies from one application to another, 6190because the options available depend inevitably on whether the 6191application developer has provided any hooks for you to hang your own 6192code on and, if there are such hooks, what they allow you to do.(1) For 6193example... 6194 6195 • If the application permits you to load and execute any Guile code, 6196 the world is your oyster. You can extend the application in any 6197 way that you choose. 6198 6199 • A more cautious application might allow you to load and execute 6200 Guile code, but only in a “safe” environment, where the interface 6201 available is restricted by the application from the standard Guile 6202 API. 6203 6204 • Or a really fearful application might not provide a hook to really 6205 execute user code at all, but just use Scheme syntax as a 6206 convenient way for users to specify application data or 6207 configuration options. 6208 6209 In the last two cases, what you can do is, by definition, restricted 6210by the application, and you should refer to the application’s own manual 6211to find out your options. 6212 6213 The most well known example of the first case is Emacs, with its 6214extension language Emacs Lisp: as well as being a text editor, Emacs 6215supports the loading and execution of arbitrary Emacs Lisp code. The 6216result of such openness has been dramatic: Emacs now benefits from 6217user-contributed Emacs Lisp libraries that extend the basic editing 6218function to do everything from reading news to psychoanalysis and 6219playing adventure games. The only limitation is that extensions are 6220restricted to the functionality provided by Emacs’s built-in set of 6221primitive operations. For example, you can interact and display data by 6222manipulating the contents of an Emacs buffer, but you can’t pop-up and 6223draw a window with a layout that is totally different to the Emacs 6224standard. 6225 6226 This situation with a Guile application that supports the loading of 6227arbitrary user code is similar, except perhaps even more so, because 6228Guile also supports the loading of extension libraries written in C. 6229This last point enables user code to add new primitive operations to 6230Guile, and so to bypass the limitation present in Emacs Lisp. 6231 6232 At this point, the distinction between an application developer and 6233an application user becomes rather blurred. Instead of seeing yourself 6234as a user extending an application, you could equally well say that you 6235are developing a new application of your own using some of the primitive 6236functionality provided by the original application. As such, all the 6237discussions of the preceding sections of this chapter are relevant to 6238how you can proceed with developing your extension. 6239 6240 ---------- Footnotes ---------- 6241 6242 (1) Of course, in the world of free software, you always have the 6243freedom to modify the application’s source code to your own 6244requirements. Here we are concerned with the extension options that the 6245application has provided for without your needing to modify its source 6246code. 6247 6248 6249File: guile.info, Node: Autoconf Support, Prev: Programming Overview, Up: Programming in C 6250 62515.8 Autoconf Support 6252==================== 6253 6254Autoconf, a part of the GNU build system, makes it easy for users to 6255build your package. This section documents Guile’s Autoconf support. 6256 6257* Menu: 6258 6259* Autoconf Background:: Why use autoconf? 6260* Autoconf Macros:: The GUILE_* macros. 6261* Using Autoconf Macros:: How to use them, plus examples. 6262 6263 6264File: guile.info, Node: Autoconf Background, Next: Autoconf Macros, Up: Autoconf Support 6265 62665.8.1 Autoconf Background 6267------------------------- 6268 6269As explained in the ‘GNU Autoconf Manual’, any package needs 6270configuration at build-time (*note Introduction: (autoconf)Top.). If 6271your package uses Guile (or uses a package that in turn uses Guile), you 6272probably need to know what specific Guile features are available and 6273details about them. 6274 6275 The way to do this is to write feature tests and arrange for their 6276execution by the ‘configure’ script, typically by adding the tests to 6277‘configure.ac’, and running ‘autoconf’ to create ‘configure’. Users of 6278your package then run ‘configure’ in the normal way. 6279 6280 Macros are a way to make common feature tests easy to express. 6281Autoconf provides a wide range of macros (*note (autoconf)Existing 6282Tests::), and Guile installation provides Guile-specific tests in the 6283areas of: program detection, compilation flags reporting, and Scheme 6284module checks. 6285 6286 6287File: guile.info, Node: Autoconf Macros, Next: Using Autoconf Macros, Prev: Autoconf Background, Up: Autoconf Support 6288 62895.8.2 Autoconf Macros 6290--------------------- 6291 6292As mentioned earlier in this chapter, Guile supports parallel 6293installation, and uses ‘pkg-config’ to let the user choose which version 6294of Guile they are interested in. ‘pkg-config’ has its own set of 6295Autoconf macros that are probably installed on most every development 6296system. The most useful of these macros is ‘PKG_CHECK_MODULES’. 6297 6298 PKG_CHECK_MODULES([GUILE], [guile-3.0]) 6299 6300 This example looks for Guile and sets the ‘GUILE_CFLAGS’ and 6301‘GUILE_LIBS’ variables accordingly, or prints an error and exits if 6302Guile was not found. 6303 6304 Guile comes with additional Autoconf macros providing more 6305information, installed as ‘PREFIX/share/aclocal/guile.m4’. Their names 6306all begin with ‘GUILE_’. 6307 6308 -- Autoconf Macro: GUILE_PKG [VERSIONS] 6309 6310 This macro runs the ‘pkg-config’ tool to find development files for 6311 an available version of Guile. 6312 6313 By default, this macro will search for the latest stable version of 6314 Guile (e.g. 3.0), falling back to the previous stable version 6315 (e.g. 2.2) if it is available. If no guile-VERSION.pc file is 6316 found, an error is signalled. The found version is stored in 6317 GUILE_EFFECTIVE_VERSION. 6318 6319 If ‘GUILE_PROGS’ was already invoked, this macro ensures that the 6320 development files have the same effective version as the Guile 6321 program. 6322 6323 GUILE_EFFECTIVE_VERSION is marked for substitution, as by 6324 ‘AC_SUBST’. 6325 6326 -- Autoconf Macro: GUILE_FLAGS 6327 6328 This macro runs the ‘pkg-config’ tool to find out how to compile 6329 and link programs against Guile. It sets four variables: 6330 GUILE_CFLAGS, GUILE_LDFLAGS, GUILE_LIBS, and GUILE_LTLIBS. 6331 6332 GUILE_CFLAGS: flags to pass to a C or C++ compiler to build code 6333 that uses Guile header files. This is almost always just one or 6334 more ‘-I’ flags. 6335 6336 GUILE_LDFLAGS: flags to pass to the compiler to link a program 6337 against Guile. This includes ‘-lguile-VERSION’ for the Guile 6338 library itself, and may also include one or more ‘-L’ flag to tell 6339 the compiler where to find the libraries. But it does not include 6340 flags that influence the program’s runtime search path for 6341 libraries, and will therefore lead to a program that fails to 6342 start, unless all necessary libraries are installed in a standard 6343 location such as ‘/usr/lib’. 6344 6345 GUILE_LIBS and GUILE_LTLIBS: flags to pass to the compiler or to 6346 libtool, respectively, to link a program against Guile. It 6347 includes flags that augment the program’s runtime search path for 6348 libraries, so that shared libraries will be found at the location 6349 where they were during linking, even in non-standard locations. 6350 GUILE_LIBS is to be used when linking the program directly with the 6351 compiler, whereas GUILE_LTLIBS is to be used when linking the 6352 program is done through libtool. 6353 6354 The variables are marked for substitution, as by ‘AC_SUBST’. 6355 6356 -- Autoconf Macro: GUILE_SITE_DIR 6357 6358 This looks for Guile’s "site" directories. The variable GUILE_SITE 6359 will be set to Guile’s "site" directory for Scheme source files 6360 (usually something like PREFIX/share/guile/site). 6361 GUILE_SITE_CCACHE will be set to the directory for compiled Scheme 6362 files also known as ‘.go’ files (usually something like 6363 PREFIX/lib/guile/GUILE_EFFECTIVE_VERSION/site-ccache). 6364 GUILE_EXTENSION will be set to the directory for compiled C 6365 extensions (usually something like 6366 PREFIX/lib/guile/GUILE_EFFECTIVE_VERSION/extensions). The latter 6367 two are set to blank if the particular version of Guile does not 6368 support them. Note that this macro will run the macros ‘GUILE_PKG’ 6369 and ‘GUILE_PROGS’ if they have not already been run. 6370 6371 The variables are marked for substitution, as by ‘AC_SUBST’. 6372 6373 -- Autoconf Macro: GUILE_PROGS [VERSION] 6374 6375 This macro looks for programs ‘guile’ and ‘guild’, setting 6376 variables GUILE and GUILD to their paths, respectively. The macro 6377 will attempt to find ‘guile’ with the suffix of ‘-X.Y’, followed by 6378 looking for it with the suffix ‘X.Y’, and then fall back to looking 6379 for ‘guile’ with no suffix. If ‘guile’ is still not found, signal 6380 an error. The suffix, if any, that was required to find ‘guile’ 6381 will be used for ‘guild’ as well. 6382 6383 By default, this macro will search for the latest stable version of 6384 Guile (e.g. 3.0). x.y or x.y.z versions can be specified. If an 6385 older version is found, the macro will signal an error. 6386 6387 The effective version of the found ‘guile’ is set to 6388 GUILE_EFFECTIVE_VERSION. This macro ensures that the effective 6389 version is compatible with the result of a previous invocation of 6390 ‘GUILE_FLAGS’, if any. 6391 6392 As a legacy interface, it also looks for ‘guile-config’ and 6393 ‘guile-tools’, setting GUILE_CONFIG and GUILE_TOOLS. 6394 6395 The variables are marked for substitution, as by ‘AC_SUBST’. 6396 6397 -- Autoconf Macro: GUILE_CHECK_RETVAL var check 6398 6399 VAR is a shell variable name to be set to the return value. CHECK 6400 is a Guile Scheme expression, evaluated with "$GUILE -c", and 6401 returning either 0 or non-#f to indicate the check passed. Non-0 6402 number or #f indicates failure. Avoid using the character "#" 6403 since that confuses autoconf. 6404 6405 -- Autoconf Macro: GUILE_MODULE_CHECK var module featuretest 6406 description 6407 6408 VAR is a shell variable name to be set to "yes" or "no". MODULE is 6409 a list of symbols, like: (ice-9 common-list). FEATURETEST is an 6410 expression acceptable to GUILE_CHECK, q.v. DESCRIPTION is a 6411 present-tense verb phrase (passed to AC_MSG_CHECKING). 6412 6413 -- Autoconf Macro: GUILE_MODULE_AVAILABLE var module 6414 6415 VAR is a shell variable name to be set to "yes" or "no". MODULE is 6416 a list of symbols, like: (ice-9 common-list). 6417 6418 -- Autoconf Macro: GUILE_MODULE_REQUIRED symlist 6419 6420 SYMLIST is a list of symbols, WITHOUT surrounding parens, like: 6421 ice-9 common-list. 6422 6423 -- Autoconf Macro: GUILE_MODULE_EXPORTS var module modvar 6424 6425 VAR is a shell variable to be set to "yes" or "no". MODULE is a 6426 list of symbols, like: (ice-9 common-list). MODVAR is the Guile 6427 Scheme variable to check. 6428 6429 -- Autoconf Macro: GUILE_MODULE_REQUIRED_EXPORT module modvar 6430 6431 MODULE is a list of symbols, like: (ice-9 common-list). MODVAR is 6432 the Guile Scheme variable to check. 6433 6434 6435File: guile.info, Node: Using Autoconf Macros, Prev: Autoconf Macros, Up: Autoconf Support 6436 64375.8.3 Using Autoconf Macros 6438--------------------------- 6439 6440Using the autoconf macros is straightforward: Add the macro "calls" 6441(actually instantiations) to ‘configure.ac’, run ‘aclocal’, and finally, 6442run ‘autoconf’. If your system doesn’t have guile.m4 installed, place 6443the desired macro definitions (‘AC_DEFUN’ forms) in ‘acinclude.m4’, and 6444‘aclocal’ will do the right thing. 6445 6446 Some of the macros can be used inside normal shell constructs: ‘if 6447foo ; then GUILE_BAZ ; fi’, but this is not guaranteed. It’s probably a 6448good idea to instantiate macros at top-level. 6449 6450 We now include two examples, one simple and one complicated. 6451 6452 The first example is for a package that uses libguile, and thus needs 6453to know how to compile and link against it. So we use 6454‘PKG_CHECK_MODULES’ to set the vars ‘GUILE_CFLAGS’ and ‘GUILE_LIBS’, 6455which are automatically substituted in the Makefile. 6456 6457 In configure.ac: 6458 6459 PKG_CHECK_MODULES([GUILE], [guile-3.0]) 6460 6461 In Makefile.in: 6462 6463 GUILE_CFLAGS = @GUILE_CFLAGS@ 6464 GUILE_LIBS = @GUILE_LIBS@ 6465 6466 myprog.o: myprog.c 6467 $(CC) -o $ $(GUILE_CFLAGS) $< 6468 myprog: myprog.o 6469 $(CC) -o $ $< $(GUILE_LIBS) 6470 6471 The second example is for a package of Guile Scheme modules that uses 6472an external program and other Guile Scheme modules (some might call this 6473a "pure scheme" package). So we use the ‘GUILE_SITE_DIR’ macro, a 6474regular ‘AC_PATH_PROG’ macro, and the ‘GUILE_MODULE_AVAILABLE’ macro. 6475 6476 In configure.ac: 6477 6478 GUILE_SITE_DIR 6479 6480 probably_wont_work="" 6481 6482 # pgtype pgtable 6483 GUILE_MODULE_AVAILABLE(have_guile_pg, (database postgres)) 6484 test $have_guile_pg = no && 6485 probably_wont_work="(my pgtype) (my pgtable) $probably_wont_work" 6486 6487 # gpgutils 6488 AC_PATH_PROG(GNUPG,gpg) 6489 test x"$GNUPG" = x && 6490 probably_wont_work="(my gpgutils) $probably_wont_work" 6491 6492 if test ! "$probably_wont_work" = "" ; then 6493 p=" ***" 6494 echo 6495 echo "$p" 6496 echo "$p NOTE:" 6497 echo "$p The following modules probably won't work:" 6498 echo "$p $probably_wont_work" 6499 echo "$p They can be installed anyway, and will work if their" 6500 echo "$p dependencies are installed later. Please see README." 6501 echo "$p" 6502 echo 6503 fi 6504 6505 In Makefile.in: 6506 6507 instdir = @GUILE_SITE@/my 6508 6509 install: 6510 $(INSTALL) my/*.scm $(instdir) 6511 6512 6513File: guile.info, Node: API Reference, Next: Guile Modules, Prev: Programming in C, Up: Top 6514 65156 API Reference 6516*************** 6517 6518Guile provides an application programming interface (“API”) to 6519developers in two core languages: Scheme and C. This part of the manual 6520contains reference documentation for all of the functionality that is 6521available through both Scheme and C interfaces. 6522 6523* Menu: 6524 6525* API Overview:: Overview of the Guile API. 6526* Deprecation:: Obsolete back-compatible APIs. 6527* The SCM Type:: The fundamental data type for C code. 6528* Initialization:: Initializing Guile. 6529* Snarfing Macros:: Macros for snarfing initialization actions. 6530* Data Types:: Representing values in Guile. 6531* Procedures:: Procedures. 6532* Macros:: Extending the syntax of Scheme. 6533* Utility Functions:: General utility functions. 6534* Binding Constructs:: Definitions and variable bindings. 6535* Control Mechanisms:: Controlling the flow of program execution. 6536* Input and Output:: Ports, reading and writing. 6537* Regular Expressions:: Pattern matching and substitution. 6538* LALR(1) Parsing:: Generating LALR(1) parsers. 6539* PEG Parsing:: Parsing Expression Grammars. 6540* Read/Load/Eval/Compile:: Reading and evaluating Scheme code. 6541* Memory Management:: Memory management and garbage collection. 6542* Modules:: Designing reusable code libraries. 6543* Foreign Function Interface:: Interacting with C procedures and data. 6544* Foreign Objects:: Defining new data types in C. 6545* Smobs:: Use foreign objects instead. 6546* Scheduling:: Threads, mutexes, asyncs and dynamic roots. 6547* Options and Config:: Configuration, features and runtime options. 6548* Other Languages:: Emacs Lisp, ECMAScript, and more. 6549* Internationalization:: Support for gettext, etc. 6550* Debugging:: Debugging infrastructure and Scheme interface. 6551* Code Coverage:: Gathering code coverage data. 6552 6553 6554File: guile.info, Node: API Overview, Next: Deprecation, Up: API Reference 6555 65566.1 Overview of the Guile API 6557============================= 6558 6559Guile’s application programming interface (“API”) makes functionality 6560available that an application developer can use in either C or Scheme 6561programming. The interface consists of “elements” that may be macros, 6562functions or variables in C, and procedures, variables, syntax or other 6563types of object in Scheme. 6564 6565 Many elements are available to both Scheme and C, in a form that is 6566appropriate. For example, the ‘assq’ Scheme procedure is also available 6567as ‘scm_assq’ to C code. These elements are documented only once, 6568addressing both the Scheme and C aspects of them. 6569 6570 The Scheme name of an element is related to its C name in a regular 6571way. Also, a C function takes its parameters in a systematic way. 6572 6573 Normally, the name of a C function can be derived given its Scheme 6574name, using some simple textual transformations: 6575 6576 • Replace ‘-’ (hyphen) with ‘_’ (underscore). 6577 6578 • Replace ‘?’ (question mark) with ‘_p’. 6579 6580 • Replace ‘!’ (exclamation point) with ‘_x’. 6581 6582 • Replace internal ‘->’ with ‘_to_’. 6583 6584 • Replace ‘<=’ (less than or equal) with ‘_leq’. 6585 6586 • Replace ‘>=’ (greater than or equal) with ‘_geq’. 6587 6588 • Replace ‘<’ (less than) with ‘_less’. 6589 6590 • Replace ‘>’ (greater than) with ‘_gr’. 6591 6592 • Prefix with ‘scm_’. 6593 6594 A C function always takes a fixed number of arguments of type ‘SCM’, 6595even when the corresponding Scheme function takes a variable number. 6596 6597 For some Scheme functions, some last arguments are optional; the 6598corresponding C function must always be invoked with all optional 6599arguments specified. To get the effect as if an argument has not been 6600specified, pass ‘SCM_UNDEFINED’ as its value. You can not do this for 6601an argument in the middle; when one argument is ‘SCM_UNDEFINED’ all the 6602ones following it must be ‘SCM_UNDEFINED’ as well. 6603 6604 Some Scheme functions take an arbitrary number of _rest_ arguments; 6605the corresponding C function must be invoked with a list of all these 6606arguments. This list is always the last argument of the C function. 6607 6608 These two variants can also be combined. 6609 6610 The type of the return value of a C function that corresponds to a 6611Scheme function is always ‘SCM’. In the descriptions below, types are 6612therefore often omitted but for the return value and for the arguments. 6613 6614 6615File: guile.info, Node: Deprecation, Next: The SCM Type, Prev: API Overview, Up: API Reference 6616 66176.2 Deprecation 6618=============== 6619 6620From time to time functions and other features of Guile become obsolete. 6621Guile’s “deprecation” is a mechanism that can help you cope with this. 6622 6623 When you use a feature that is deprecated, you will likely get a 6624warning message at run-time. Also, if you have a new enough toolchain, 6625using a deprecated function from ‘libguile’ will cause a link-time 6626warning. 6627 6628 The primary source for information about just what interfaces are 6629deprecated in a given release is the file ‘NEWS’. That file also 6630documents what you should use instead of the obsoleted things. 6631 6632 The file ‘README’ contains instructions on how to control the 6633inclusion or removal of the deprecated features from the public API of 6634Guile, and how to control the deprecation warning messages. 6635 6636 The idea behind this mechanism is that normally all deprecated 6637interfaces are available, but you get feedback when compiling and 6638running code that uses them, so that you can migrate to the newer APIs 6639at your leisure. 6640 6641 6642File: guile.info, Node: The SCM Type, Next: Initialization, Prev: Deprecation, Up: API Reference 6643 66446.3 The SCM Type 6645================ 6646 6647Guile represents all Scheme values with the single C type ‘SCM’. For an 6648introduction to this topic, *Note Dynamic Types::. 6649 6650 -- C Type: SCM 6651 ‘SCM’ is the user level abstract C type that is used to represent 6652 all of Guile’s Scheme objects, no matter what the Scheme object 6653 type is. No C operation except assignment is guaranteed to work 6654 with variables of type ‘SCM’, so you should only use macros and 6655 functions to work with ‘SCM’ values. Values are converted between 6656 C data types and the ‘SCM’ type with utility functions and macros. 6657 6658 -- C Type: scm_t_bits 6659 ‘scm_t_bits’ is an unsigned integral data type that is guaranteed 6660 to be large enough to hold all information that is required to 6661 represent any Scheme object. While this data type is mostly used 6662 to implement Guile’s internals, the use of this type is also 6663 necessary to write certain kinds of extensions to Guile. 6664 6665 -- C Type: scm_t_signed_bits 6666 This is a signed integral type of the same size as ‘scm_t_bits’. 6667 6668 -- C Macro: scm_t_bits SCM_UNPACK (SCM X) 6669 Transforms the ‘SCM’ value X into its representation as an integral 6670 type. Only after applying ‘SCM_UNPACK’ it is possible to access 6671 the bits and contents of the ‘SCM’ value. 6672 6673 -- C Macro: SCM SCM_PACK (scm_t_bits X) 6674 Takes a valid integral representation of a Scheme object and 6675 transforms it into its representation as a ‘SCM’ value. 6676 6677 6678File: guile.info, Node: Initialization, Next: Snarfing Macros, Prev: The SCM Type, Up: API Reference 6679 66806.4 Initializing Guile 6681====================== 6682 6683Each thread that wants to use functions from the Guile API needs to put 6684itself into guile mode with either ‘scm_with_guile’ or ‘scm_init_guile’. 6685The global state of Guile is initialized automatically when the first 6686thread enters guile mode. 6687 6688 When a thread wants to block outside of a Guile API function, it 6689should leave guile mode temporarily with ‘scm_without_guile’, *Note 6690Blocking::. 6691 6692 Threads that are created by ‘call-with-new-thread’ or 6693‘scm_spawn_thread’ start out in guile mode so you don’t need to 6694initialize them. 6695 6696 -- C Function: void * scm_with_guile (void *(*func)(void *), void 6697 *data) 6698 Call FUNC, passing it DATA and return what FUNC returns. While 6699 FUNC is running, the current thread is in guile mode and can thus 6700 use the Guile API. 6701 6702 When ‘scm_with_guile’ is called from guile mode, the thread remains 6703 in guile mode when ‘scm_with_guile’ returns. 6704 6705 Otherwise, it puts the current thread into guile mode and, if 6706 needed, gives it a Scheme representation that is contained in the 6707 list returned by ‘all-threads’, for example. This Scheme 6708 representation is not removed when ‘scm_with_guile’ returns so that 6709 a given thread is always represented by the same Scheme value 6710 during its lifetime, if at all. 6711 6712 When this is the first thread that enters guile mode, the global 6713 state of Guile is initialized before calling ‘func’. 6714 6715 The function FUNC is called via ‘scm_with_continuation_barrier’; 6716 thus, ‘scm_with_guile’ returns exactly once. 6717 6718 When ‘scm_with_guile’ returns, the thread is no longer in guile 6719 mode (except when ‘scm_with_guile’ was called from guile mode, see 6720 above). Thus, only ‘func’ can store ‘SCM’ variables on the stack 6721 and be sure that they are protected from the garbage collector. 6722 See ‘scm_init_guile’ for another approach at initializing Guile 6723 that does not have this restriction. 6724 6725 It is OK to call ‘scm_with_guile’ while a thread has temporarily 6726 left guile mode via ‘scm_without_guile’. It will then simply 6727 temporarily enter guile mode again. 6728 6729 -- C Function: void scm_init_guile () 6730 Arrange things so that all of the code in the current thread 6731 executes as if from within a call to ‘scm_with_guile’. That is, 6732 all functions called by the current thread can assume that ‘SCM’ 6733 values on their stack frames are protected from the garbage 6734 collector (except when the thread has explicitly left guile mode, 6735 of course). 6736 6737 When ‘scm_init_guile’ is called from a thread that already has been 6738 in guile mode once, nothing happens. This behavior matters when 6739 you call ‘scm_init_guile’ while the thread has only temporarily 6740 left guile mode: in that case the thread will not be in guile mode 6741 after ‘scm_init_guile’ returns. Thus, you should not use 6742 ‘scm_init_guile’ in such a scenario. 6743 6744 When a uncaught throw happens in a thread that has been put into 6745 guile mode via ‘scm_init_guile’, a short message is printed to the 6746 current error port and the thread is exited via ‘scm_pthread_exit 6747 (NULL)’. No restrictions are placed on continuations. 6748 6749 The function ‘scm_init_guile’ might not be available on all 6750 platforms since it requires some stack-bounds-finding magic that 6751 might not have been ported to all platforms that Guile runs on. 6752 Thus, if you can, it is better to use ‘scm_with_guile’ or its 6753 variation ‘scm_boot_guile’ instead of this function. 6754 6755 -- C Function: void scm_boot_guile (int ARGC, char **ARGV, void 6756 (*MAIN_FUNC) (void *DATA, int ARGC, char **ARGV), void *DATA) 6757 Enter guile mode as with ‘scm_with_guile’ and call MAIN_FUNC, 6758 passing it DATA, ARGC, and ARGV as indicated. When MAIN_FUNC 6759 returns, ‘scm_boot_guile’ calls ‘exit (0)’; ‘scm_boot_guile’ never 6760 returns. If you want some other exit value, have MAIN_FUNC call 6761 ‘exit’ itself. If you don’t want to exit at all, use 6762 ‘scm_with_guile’ instead of ‘scm_boot_guile’. 6763 6764 The function ‘scm_boot_guile’ arranges for the Scheme 6765 ‘command-line’ function to return the strings given by ARGC and 6766 ARGV. If MAIN_FUNC modifies ARGC or ARGV, it should call 6767 ‘scm_set_program_arguments’ with the final list, so Scheme code 6768 will know which arguments have been processed (*note Runtime 6769 Environment::). 6770 6771 -- C Function: void scm_shell (int ARGC, char **ARGV) 6772 Process command-line arguments in the manner of the ‘guile’ 6773 executable. This includes loading the normal Guile initialization 6774 files, interacting with the user or running any scripts or 6775 expressions specified by ‘-s’ or ‘-e’ options, and then exiting. 6776 *Note Invoking Guile::, for more details. 6777 6778 Since this function does not return, you must do all 6779 application-specific initialization before calling this function. 6780 6781 6782File: guile.info, Node: Snarfing Macros, Next: Data Types, Prev: Initialization, Up: API Reference 6783 67846.5 Snarfing Macros 6785=================== 6786 6787The following macros do two different things: when compiled normally, 6788they expand in one way; when processed during snarfing, they cause the 6789‘guile-snarf’ program to pick up some initialization code, *Note 6790Function Snarfing::. 6791 6792 The descriptions below use the term ‘normally’ to refer to the case 6793when the code is compiled normally, and ‘while snarfing’ when the code 6794is processed by ‘guile-snarf’. 6795 6796 -- C Macro: SCM_SNARF_INIT (code) 6797 6798 Normally, ‘SCM_SNARF_INIT’ expands to nothing; while snarfing, it 6799 causes CODE to be included in the initialization action file, 6800 followed by a semicolon. 6801 6802 This is the fundamental macro for snarfing initialization actions. 6803 The more specialized macros below use it internally. 6804 6805 -- C Macro: SCM_DEFINE (c_name, scheme_name, req, opt, var, arglist, 6806 docstring) 6807 6808 Normally, this macro expands into 6809 6810 static const char s_C_NAME[] = SCHEME_NAME; 6811 SCM 6812 C_NAME ARGLIST 6813 6814 While snarfing, it causes 6815 6816 scm_c_define_gsubr (s_C_NAME, REQ, OPT, VAR, 6817 C_NAME); 6818 6819 to be added to the initialization actions. Thus, you can use it to 6820 declare a C function named C_NAME that will be made available to 6821 Scheme with the name SCHEME_NAME. 6822 6823 Note that the ARGLIST argument must have parentheses around it. 6824 6825 -- C Macro: SCM_SYMBOL (c_name, scheme_name) 6826 -- C Macro: SCM_GLOBAL_SYMBOL (c_name, scheme_name) 6827 Normally, these macros expand into 6828 6829 static SCM C_NAME 6830 6831 or 6832 6833 SCM C_NAME 6834 6835 respectively. While snarfing, they both expand into the 6836 initialization code 6837 6838 C_NAME = scm_permanent_object (scm_from_locale_symbol (SCHEME_NAME)); 6839 6840 Thus, you can use them declare a static or global variable of type 6841 ‘SCM’ that will be initialized to the symbol named SCHEME_NAME. 6842 6843 -- C Macro: SCM_KEYWORD (c_name, scheme_name) 6844 -- C Macro: SCM_GLOBAL_KEYWORD (c_name, scheme_name) 6845 Normally, these macros expand into 6846 6847 static SCM C_NAME 6848 6849 or 6850 6851 SCM C_NAME 6852 6853 respectively. While snarfing, they both expand into the 6854 initialization code 6855 6856 C_NAME = scm_permanent_object (scm_c_make_keyword (SCHEME_NAME)); 6857 6858 Thus, you can use them declare a static or global variable of type 6859 ‘SCM’ that will be initialized to the keyword named SCHEME_NAME. 6860 6861 -- C Macro: SCM_VARIABLE (c_name, scheme_name) 6862 -- C Macro: SCM_GLOBAL_VARIABLE (c_name, scheme_name) 6863 These macros are equivalent to ‘SCM_VARIABLE_INIT’ and 6864 ‘SCM_GLOBAL_VARIABLE_INIT’, respectively, with a VALUE of 6865 ‘SCM_BOOL_F’. 6866 6867 -- C Macro: SCM_VARIABLE_INIT (c_name, scheme_name, value) 6868 -- C Macro: SCM_GLOBAL_VARIABLE_INIT (c_name, scheme_name, value) 6869 6870 Normally, these macros expand into 6871 6872 static SCM C_NAME 6873 6874 or 6875 6876 SCM C_NAME 6877 6878 respectively. While snarfing, they both expand into the 6879 initialization code 6880 6881 C_NAME = scm_permanent_object (scm_c_define (SCHEME_NAME, VALUE)); 6882 6883 Thus, you can use them declare a static or global C variable of 6884 type ‘SCM’ that will be initialized to the object representing the 6885 Scheme variable named SCHEME_NAME in the current module. The 6886 variable will be defined when it doesn’t already exist. It is 6887 always set to VALUE. 6888 6889 6890File: guile.info, Node: Data Types, Next: Procedures, Prev: Snarfing Macros, Up: API Reference 6891 68926.6 Data Types 6893============== 6894 6895Guile’s data types form a powerful built-in library of representations 6896and functionality that you can apply to your problem domain. This 6897chapter surveys the data types built-in to Guile, from the simple to the 6898complex. 6899 6900* Menu: 6901 6902* Booleans:: True/false values. 6903* Numbers:: Numerical data types. 6904* Characters:: Single characters. 6905* Character Sets:: Sets of characters. 6906* Strings:: Sequences of characters. 6907* Symbols:: Symbols. 6908* Keywords:: Self-quoting, customizable display keywords. 6909* Pairs:: Scheme’s basic building block. 6910* Lists:: Special list functions supported by Guile. 6911* Vectors:: One-dimensional arrays of Scheme objects. 6912* Bit Vectors:: Vectors of bits. 6913* Bytevectors:: Sequences of bytes. 6914* Arrays:: Multidimensional matrices. 6915* VLists:: Vector-like lists. 6916* Record Overview:: Walking through the maze of record APIs. 6917* SRFI-9 Records:: The standard, recommended record API. 6918* Records:: Guile’s historical record API. 6919* Structures:: Low-level record representation. 6920* Dictionary Types:: About dictionary types in general. 6921* Association Lists:: List-based dictionaries. 6922* VHashes:: VList-based dictionaries. 6923* Hash Tables:: Table-based dictionaries. 6924* Other Types:: Other sections describe data types too. 6925 6926 6927File: guile.info, Node: Booleans, Next: Numbers, Up: Data Types 6928 69296.6.1 Booleans 6930-------------- 6931 6932The two boolean values are ‘#t’ for true and ‘#f’ for false. They can 6933also be written as ‘#true’ and ‘#false’, as per R7RS. 6934 6935 Boolean values are returned by predicate procedures, such as the 6936general equality predicates ‘eq?’, ‘eqv?’ and ‘equal?’ (*note 6937Equality::) and numerical and string comparison operators like 6938‘string=?’ (*note String Comparison::) and ‘<=’ (*note Comparison::). 6939 6940 (<= 3 8) 6941 ⇒ #t 6942 6943 (<= 3 -3) 6944 ⇒ #f 6945 6946 (equal? "house" "houses") 6947 ⇒ #f 6948 6949 (eq? #f #f) 6950 ⇒ 6951 #t 6952 6953 In test condition contexts like ‘if’ and ‘cond’ (*note 6954Conditionals::), where a group of subexpressions will be evaluated only 6955if a CONDITION expression evaluates to “true”, “true” means any value at 6956all except ‘#f’. 6957 6958 (if #t "yes" "no") 6959 ⇒ "yes" 6960 6961 (if 0 "yes" "no") 6962 ⇒ "yes" 6963 6964 (if #f "yes" "no") 6965 ⇒ "no" 6966 6967 A result of this asymmetry is that typical Scheme source code more 6968often uses ‘#f’ explicitly than ‘#t’: ‘#f’ is necessary to represent an 6969‘if’ or ‘cond’ false value, whereas ‘#t’ is not necessary to represent 6970an ‘if’ or ‘cond’ true value. 6971 6972 It is important to note that ‘#f’ is *not* equivalent to any other 6973Scheme value. In particular, ‘#f’ is not the same as the number 0 (like 6974in C and C++), and not the same as the “empty list” (like in some Lisp 6975dialects). 6976 6977 In C, the two Scheme boolean values are available as the two 6978constants ‘SCM_BOOL_T’ for ‘#t’ and ‘SCM_BOOL_F’ for ‘#f’. Care must be 6979taken with the false value ‘SCM_BOOL_F’: it is not false when used in C 6980conditionals. In order to test for it, use ‘scm_is_false’ or 6981‘scm_is_true’. 6982 6983 -- Scheme Procedure: not x 6984 -- C Function: scm_not (x) 6985 Return ‘#t’ if X is ‘#f’, else return ‘#f’. 6986 6987 -- Scheme Procedure: boolean? obj 6988 -- C Function: scm_boolean_p (obj) 6989 Return ‘#t’ if OBJ is either ‘#t’ or ‘#f’, else return ‘#f’. 6990 6991 -- C Macro: SCM SCM_BOOL_T 6992 The ‘SCM’ representation of the Scheme object ‘#t’. 6993 6994 -- C Macro: SCM SCM_BOOL_F 6995 The ‘SCM’ representation of the Scheme object ‘#f’. 6996 6997 -- C Function: int scm_is_true (SCM obj) 6998 Return ‘0’ if OBJ is ‘#f’, else return ‘1’. 6999 7000 -- C Function: int scm_is_false (SCM obj) 7001 Return ‘1’ if OBJ is ‘#f’, else return ‘0’. 7002 7003 -- C Function: int scm_is_bool (SCM obj) 7004 Return ‘1’ if OBJ is either ‘#t’ or ‘#f’, else return ‘0’. 7005 7006 -- C Function: SCM scm_from_bool (int val) 7007 Return ‘#f’ if VAL is ‘0’, else return ‘#t’. 7008 7009 -- C Function: int scm_to_bool (SCM val) 7010 Return ‘1’ if VAL is ‘SCM_BOOL_T’, return ‘0’ when VAL is 7011 ‘SCM_BOOL_F’, else signal a ‘wrong type’ error. 7012 7013 You should probably use ‘scm_is_true’ instead of this function when 7014 you just want to test a ‘SCM’ value for trueness. 7015 7016 7017File: guile.info, Node: Numbers, Next: Characters, Prev: Booleans, Up: Data Types 7018 70196.6.2 Numerical data types 7020-------------------------- 7021 7022Guile supports a rich “tower” of numerical types — integer, rational, 7023real and complex — and provides an extensive set of mathematical and 7024scientific functions for operating on numerical data. This section of 7025the manual documents those types and functions. 7026 7027 You may also find it illuminating to read R5RS’s presentation of 7028numbers in Scheme, which is particularly clear and accessible: see *note 7029(r5rs)Numbers::. 7030 7031* Menu: 7032 7033* Numerical Tower:: Scheme’s numerical "tower". 7034* Integers:: Whole numbers. 7035* Reals and Rationals:: Real and rational numbers. 7036* Complex Numbers:: Complex numbers. 7037* Exactness:: Exactness and inexactness. 7038* Number Syntax:: Read syntax for numerical data. 7039* Integer Operations:: Operations on integer values. 7040* Comparison:: Comparison predicates. 7041* Conversion:: Converting numbers to and from strings. 7042* Complex:: Complex number operations. 7043* Arithmetic:: Arithmetic functions. 7044* Scientific:: Scientific functions. 7045* Bitwise Operations:: Logical AND, OR, NOT, and so on. 7046* Random:: Random number generation. 7047 7048 7049File: guile.info, Node: Numerical Tower, Next: Integers, Up: Numbers 7050 70516.6.2.1 Scheme’s Numerical “Tower” 7052.................................. 7053 7054Scheme’s numerical “tower” consists of the following categories of 7055numbers: 7056 7057“integers” 7058 Whole numbers, positive or negative; e.g. –5, 0, 18. 7059 7060“rationals” 7061 The set of numbers that can be expressed as P/Q where P and Q are 7062 integers; e.g. 9/16 works, but pi (an irrational number) doesn’t. 7063 These include integers (N/1). 7064 7065“real numbers” 7066 The set of numbers that describes all possible positions along a 7067 one-dimensional line. This includes rationals as well as 7068 irrational numbers. 7069 7070“complex numbers” 7071 The set of numbers that describes all possible positions in a two 7072 dimensional space. This includes real as well as imaginary numbers 7073 (A+Bi, where A is the “real part”, B is the “imaginary part”, and i 7074 is the square root of −1.) 7075 7076 It is called a tower because each category “sits on” the one that 7077follows it, in the sense that every integer is also a rational, every 7078rational is also real, and every real number is also a complex number 7079(but with zero imaginary part). 7080 7081 In addition to the classification into integers, rationals, reals and 7082complex numbers, Scheme also distinguishes between whether a number is 7083represented exactly or not. For example, the result of 2*sin(pi/4) is 7084exactly 2^(1/2), but Guile can represent neither pi/4 nor 2^(1/2) 7085exactly. Instead, it stores an inexact approximation, using the C type 7086‘double’. 7087 7088 Guile can represent exact rationals of any magnitude, inexact 7089rationals that fit into a C ‘double’, and inexact complex numbers with 7090‘double’ real and imaginary parts. 7091 7092 The ‘number?’ predicate may be applied to any Scheme value to 7093discover whether the value is any of the supported numerical types. 7094 7095 -- Scheme Procedure: number? obj 7096 -- C Function: scm_number_p (obj) 7097 Return ‘#t’ if OBJ is any kind of number, else ‘#f’. 7098 7099 For example: 7100 7101 (number? 3) 7102 ⇒ #t 7103 7104 (number? "hello there!") 7105 ⇒ #f 7106 7107 (define pi 3.141592654) 7108 (number? pi) 7109 ⇒ #t 7110 7111 -- C Function: int scm_is_number (SCM obj) 7112 This is equivalent to ‘scm_is_true (scm_number_p (obj))’. 7113 7114 The next few subsections document each of Guile’s numerical data 7115types in detail. 7116 7117 7118File: guile.info, Node: Integers, Next: Reals and Rationals, Prev: Numerical Tower, Up: Numbers 7119 71206.6.2.2 Integers 7121................ 7122 7123Integers are whole numbers, that is numbers with no fractional part, 7124such as 2, 83, and −3789. 7125 7126 Integers in Guile can be arbitrarily big, as shown by the following 7127example. 7128 7129 (define (factorial n) 7130 (let loop ((n n) (product 1)) 7131 (if (= n 0) 7132 product 7133 (loop (- n 1) (* product n))))) 7134 7135 (factorial 3) 7136 ⇒ 6 7137 7138 (factorial 20) 7139 ⇒ 2432902008176640000 7140 7141 (- (factorial 45)) 7142 ⇒ -119622220865480194561963161495657715064383733760000000000 7143 7144 Readers whose background is in programming languages where integers 7145are limited by the need to fit into just 4 or 8 bytes of memory may find 7146this surprising, or suspect that Guile’s representation of integers is 7147inefficient. In fact, Guile achieves a near optimal balance of 7148convenience and efficiency by using the host computer’s native 7149representation of integers where possible, and a more general 7150representation where the required number does not fit in the native 7151form. Conversion between these two representations is automatic and 7152completely invisible to the Scheme level programmer. 7153 7154 C has a host of different integer types, and Guile offers a host of 7155functions to convert between them and the ‘SCM’ representation. For 7156example, a C ‘int’ can be handled with ‘scm_to_int’ and ‘scm_from_int’. 7157Guile also defines a few C integer types of its own, to help with 7158differences between systems. 7159 7160 C integer types that are not covered can be handled with the generic 7161‘scm_to_signed_integer’ and ‘scm_from_signed_integer’ for signed types, 7162or with ‘scm_to_unsigned_integer’ and ‘scm_from_unsigned_integer’ for 7163unsigned types. 7164 7165 Scheme integers can be exact and inexact. For example, a number 7166written as ‘3.0’ with an explicit decimal-point is inexact, but it is 7167also an integer. The functions ‘integer?’ and ‘scm_is_integer’ report 7168true for such a number, but the functions ‘exact-integer?’, 7169‘scm_is_exact_integer’, ‘scm_is_signed_integer’, and 7170‘scm_is_unsigned_integer’ only allow exact integers and thus report 7171false. Likewise, the conversion functions like ‘scm_to_signed_integer’ 7172only accept exact integers. 7173 7174 The motivation for this behavior is that the inexactness of a number 7175should not be lost silently. If you want to allow inexact integers, you 7176can explicitly insert a call to ‘inexact->exact’ or to its C equivalent 7177‘scm_inexact_to_exact’. (Only inexact integers will be converted by 7178this call into exact integers; inexact non-integers will become exact 7179fractions.) 7180 7181 -- Scheme Procedure: integer? x 7182 -- C Function: scm_integer_p (x) 7183 Return ‘#t’ if X is an exact or inexact integer number, else return 7184 ‘#f’. 7185 7186 (integer? 487) 7187 ⇒ #t 7188 7189 (integer? 3.0) 7190 ⇒ #t 7191 7192 (integer? -3.4) 7193 ⇒ #f 7194 7195 (integer? +inf.0) 7196 ⇒ #f 7197 7198 -- C Function: int scm_is_integer (SCM x) 7199 This is equivalent to ‘scm_is_true (scm_integer_p (x))’. 7200 7201 -- Scheme Procedure: exact-integer? x 7202 -- C Function: scm_exact_integer_p (x) 7203 Return ‘#t’ if X is an exact integer number, else return ‘#f’. 7204 7205 (exact-integer? 37) 7206 ⇒ #t 7207 7208 (exact-integer? 3.0) 7209 ⇒ #f 7210 7211 -- C Function: int scm_is_exact_integer (SCM x) 7212 This is equivalent to ‘scm_is_true (scm_exact_integer_p (x))’. 7213 7214 -- C Type: scm_t_int8 7215 -- C Type: scm_t_uint8 7216 -- C Type: scm_t_int16 7217 -- C Type: scm_t_uint16 7218 -- C Type: scm_t_int32 7219 -- C Type: scm_t_uint32 7220 -- C Type: scm_t_int64 7221 -- C Type: scm_t_uint64 7222 -- C Type: scm_t_intmax 7223 -- C Type: scm_t_uintmax 7224 The C types are equivalent to the corresponding ISO C types but are 7225 defined on all platforms, with the exception of ‘scm_t_int64’ and 7226 ‘scm_t_uint64’, which are only defined when a 64-bit type is 7227 available. For example, ‘scm_t_int8’ is equivalent to ‘int8_t’. 7228 7229 You can regard these definitions as a stop-gap measure until all 7230 platforms provide these types. If you know that all the platforms 7231 that you are interested in already provide these types, it is 7232 better to use them directly instead of the types provided by Guile. 7233 7234 -- C Function: int scm_is_signed_integer (SCM x, scm_t_intmax min, 7235 scm_t_intmax max) 7236 -- C Function: int scm_is_unsigned_integer (SCM x, scm_t_uintmax min, 7237 scm_t_uintmax max) 7238 Return ‘1’ when X represents an exact integer that is between MIN 7239 and MAX, inclusive. 7240 7241 These functions can be used to check whether a ‘SCM’ value will fit 7242 into a given range, such as the range of a given C integer type. 7243 If you just want to convert a ‘SCM’ value to a given C integer 7244 type, use one of the conversion functions directly. 7245 7246 -- C Function: scm_t_intmax scm_to_signed_integer (SCM x, scm_t_intmax 7247 min, scm_t_intmax max) 7248 -- C Function: scm_t_uintmax scm_to_unsigned_integer (SCM x, 7249 scm_t_uintmax min, scm_t_uintmax max) 7250 When X represents an exact integer that is between MIN and MAX 7251 inclusive, return that integer. Else signal an error, either a 7252 ‘wrong-type’ error when X is not an exact integer, or an 7253 ‘out-of-range’ error when it doesn’t fit the given range. 7254 7255 -- C Function: SCM scm_from_signed_integer (scm_t_intmax x) 7256 -- C Function: SCM scm_from_unsigned_integer (scm_t_uintmax x) 7257 Return the ‘SCM’ value that represents the integer X. This 7258 function will always succeed and will always return an exact 7259 number. 7260 7261 -- C Function: char scm_to_char (SCM x) 7262 -- C Function: signed char scm_to_schar (SCM x) 7263 -- C Function: unsigned char scm_to_uchar (SCM x) 7264 -- C Function: short scm_to_short (SCM x) 7265 -- C Function: unsigned short scm_to_ushort (SCM x) 7266 -- C Function: int scm_to_int (SCM x) 7267 -- C Function: unsigned int scm_to_uint (SCM x) 7268 -- C Function: long scm_to_long (SCM x) 7269 -- C Function: unsigned long scm_to_ulong (SCM x) 7270 -- C Function: long long scm_to_long_long (SCM x) 7271 -- C Function: unsigned long long scm_to_ulong_long (SCM x) 7272 -- C Function: size_t scm_to_size_t (SCM x) 7273 -- C Function: ssize_t scm_to_ssize_t (SCM x) 7274 -- C Function: scm_t_uintptr scm_to_uintptr_t (SCM x) 7275 -- C Function: scm_t_ptrdiff scm_to_ptrdiff_t (SCM x) 7276 -- C Function: scm_t_int8 scm_to_int8 (SCM x) 7277 -- C Function: scm_t_uint8 scm_to_uint8 (SCM x) 7278 -- C Function: scm_t_int16 scm_to_int16 (SCM x) 7279 -- C Function: scm_t_uint16 scm_to_uint16 (SCM x) 7280 -- C Function: scm_t_int32 scm_to_int32 (SCM x) 7281 -- C Function: scm_t_uint32 scm_to_uint32 (SCM x) 7282 -- C Function: scm_t_int64 scm_to_int64 (SCM x) 7283 -- C Function: scm_t_uint64 scm_to_uint64 (SCM x) 7284 -- C Function: scm_t_intmax scm_to_intmax (SCM x) 7285 -- C Function: scm_t_uintmax scm_to_uintmax (SCM x) 7286 -- C Function: scm_t_intptr scm_to_intptr_t (SCM x) 7287 -- C Function: scm_t_uintptr scm_to_uintptr_t (SCM x) 7288 When X represents an exact integer that fits into the indicated C 7289 type, return that integer. Else signal an error, either a 7290 ‘wrong-type’ error when X is not an exact integer, or an 7291 ‘out-of-range’ error when it doesn’t fit the given range. 7292 7293 The functions ‘scm_to_long_long’, ‘scm_to_ulong_long’, 7294 ‘scm_to_int64’, and ‘scm_to_uint64’ are only available when the 7295 corresponding types are. 7296 7297 -- C Function: SCM scm_from_char (char x) 7298 -- C Function: SCM scm_from_schar (signed char x) 7299 -- C Function: SCM scm_from_uchar (unsigned char x) 7300 -- C Function: SCM scm_from_short (short x) 7301 -- C Function: SCM scm_from_ushort (unsigned short x) 7302 -- C Function: SCM scm_from_int (int x) 7303 -- C Function: SCM scm_from_uint (unsigned int x) 7304 -- C Function: SCM scm_from_long (long x) 7305 -- C Function: SCM scm_from_ulong (unsigned long x) 7306 -- C Function: SCM scm_from_long_long (long long x) 7307 -- C Function: SCM scm_from_ulong_long (unsigned long long x) 7308 -- C Function: SCM scm_from_size_t (size_t x) 7309 -- C Function: SCM scm_from_ssize_t (ssize_t x) 7310 -- C Function: SCM scm_from_uintptr_t (uintptr_t x) 7311 -- C Function: SCM scm_from_ptrdiff_t (scm_t_ptrdiff x) 7312 -- C Function: SCM scm_from_int8 (scm_t_int8 x) 7313 -- C Function: SCM scm_from_uint8 (scm_t_uint8 x) 7314 -- C Function: SCM scm_from_int16 (scm_t_int16 x) 7315 -- C Function: SCM scm_from_uint16 (scm_t_uint16 x) 7316 -- C Function: SCM scm_from_int32 (scm_t_int32 x) 7317 -- C Function: SCM scm_from_uint32 (scm_t_uint32 x) 7318 -- C Function: SCM scm_from_int64 (scm_t_int64 x) 7319 -- C Function: SCM scm_from_uint64 (scm_t_uint64 x) 7320 -- C Function: SCM scm_from_intmax (scm_t_intmax x) 7321 -- C Function: SCM scm_from_uintmax (scm_t_uintmax x) 7322 -- C Function: SCM scm_from_intptr_t (scm_t_intptr x) 7323 -- C Function: SCM scm_from_uintptr_t (scm_t_uintptr x) 7324 Return the ‘SCM’ value that represents the integer X. These 7325 functions will always succeed and will always return an exact 7326 number. 7327 7328 -- C Function: void scm_to_mpz (SCM val, mpz_t rop) 7329 Assign VAL to the multiple precision integer ROP. VAL must be an 7330 exact integer, otherwise an error will be signalled. ROP must have 7331 been initialized with ‘mpz_init’ before this function is called. 7332 When ROP is no longer needed the occupied space must be freed with 7333 ‘mpz_clear’. *Note (gmp)Initializing Integers::, for details. 7334 7335 -- C Function: SCM scm_from_mpz (mpz_t val) 7336 Return the ‘SCM’ value that represents VAL. 7337 7338