Generating machine code and delivering an application independent of
development machinery are separate questions. Tcl scripting and
embedding provide concrete examples before the chapter examines
execution strategy, reflection, dependencies, and the author's
deployment preferences.
Chapter Map
characteristic features of scripting languages, quoting,
substitution, and shell automation
the Tcl language: word formation, braces, control flow, procedures,
and lists
embedding a Tcl interpreter inside C programs and building
interfaces with Tcl/Tk
compilation, interpretation, reflection, runtime dependencies, and
deployment tradeoffs
Detailed notes - 12: Compilation, interpretation, and scripting
1
languages studied so far use different execution arrangements:
Pascal, C, C++ and assembly: ordinary compiled programs
SBCL: can compile Lisp functions to machine code
saved executables can also contain a large Lisp runtime
Scheme implementations may translate through C
generated programs can still depend on a substantial runtime
machine-code generation and independence from a runtime:
separate questions, developed later in this chapter
2
execution strategy influences how programmers view their programs
the author treats compilation / interpretation as paradigms
scripting languages provide the next example
12.1 Characteristic features of scripting
languages
Command scripts automate recurring work by coordinating existing
programs through text interfaces. Variable substitution, quoting, and
evaluation determine when text remains data and when it becomes an
executable command.
Detailed notes - 12.1: Characteristic features of scripting languages
1
command languages originally describe jobs for the operating system:
which programs to run and how to run them
Bourne Shell:
already used to launch editors, compilers and our own programs
a programming language, even during ordinary terminal work
2
script: commands saved as a program to automate a recurring task
shell programming includes:
variables, assignment, branches and loops
while, until, for and case
functions; recursion is possible, though often unsuitable here
3
command scripts coordinate work performed by other programs
interpreter overhead can be small compared with that work
traditional scripting model: everything is represented as text
numbers, commands and other values can all be strings
string processing therefore receives substantial support
ordinary words can represent themselves without quotation
quoting changes how characters are interpreted:
double quotes: group words while allowing some substitutions
single quotes: preserve literal shell text
command substitution: insert a command's output in another command
command text remains data until evaluated in a command context
4
variable name and variable value must be distinguished explicitly
MY_VARIABLE=256: assign using the name, without spaces around =
$MY_VARIABLE or ${MY_VARIABLE}: retrieve the value
echo MY_VARIABLE: print the name itself
echo $MY_VARIABLE: print 256
reading a variable is an operation:
the $ marks that operation in many command languages
comparable to distinguishing a NASM label from memory at [label]
5
program text is also string data -> evaluation can execute built text
analogous to evaluating constructed S-expressions in Lisp
strings need less structure than Lisp's list representation
metaprogramming fits naturally into this execution model
6
command languages make external programs easy to combine:
launch programs and redirect their input / output
inspect and transform their output
text-based interfaces connect scripts with ordinary Unix programs
also useful in scripting languages without an interactive shell
12.2 The Tcl language
Tcl began as an embeddable command language, with Tk adding graphical
interfaces. The chapter uses classic facilities to explore runtime
script strings and application extensions, while its version preferences
belong to the book's context.
Detailed notes - 12.2: The Tcl language
1
Tcl: Tool Command Language
spelling: capital T, lower-case c and l
pronounced "tickle" or as the three letters
2
John Ousterhout developed Tcl at Berkeley; first release: 1988 original purpose: an embedded command language for applications
useful when plain configuration files are insufficient
Tk added facilities for graphical interfaces
other languages can access Tk through Tcl as well
3
the book mentions alternative implementations, including Jim / TinyTcl
its discussion reflects the implementations available then
the author criticizes additions in Tcl 8.5 and 8.6
4
backward compatibility allows the book to use the classic Tcl / Tk facilities available in version 8.4
12.2.1 The interpreter and the simplest
programs
Tcl commands return results that can be substituted into other
commands with brackets. The interpreter separates evaluating a result
from printing it, and exec captures external program output for use
within a script.
Detailed notes - 12.2.1: The interpreter and the simplest programs
1
tclsh: the Tcl interpreter
which tclsh: find its installed path
a shebang can name that interpreter directly
puts "Hello, world": print a line
chmod +x: make a saved script directly executable
# starts a comment where the interpreter expects a command
2
alternative script header: begin with /bin/sh
second line: a comment ending in a backslash
third line: exec tclsh "$0" "$@"
the same header has two interpretations:
sh ends the comment at the newline and executes the third line
exec replaces sh with tclsh, preserving the script's arguments
Tcl joins the continued comment and ignores the third line
3
advantages of the shell wrapper described in the book:
finds tclsh through PATH instead of a fixed installation path
Tcl distinguishes a variable's name from its substituted value, with
set supporting both assignment and retrieval. Strings can represent
lists and command arguments, while implementations may cache more
efficient internal representations without changing visible
semantics.
Detailed notes - 12.2.2: Variables and their values
1
Tcl's visible data model uses strings for many purposes:
numbers, booleans, variable names and command names
entire programs and individual program constructions
implementation can cache other representations internally
avoids repeatedly converting the same value
2
identifiers are strings naming commands or variables
unusual names are possible but need careful quoting
conventional letter / underscore / digit names are clearer
3
set name value: assign a value to a variable
set x 25: store 25 in x
$x: substitute x's value
substitution also works within double quotes
arithmetic updates require evaluating an expression with the value
set n [expr {$n + 1}]
4
set name: return the variable's current value
[set x] can therefore be used where $x would appear
5
strings can represent lists
lindex list index: retrieve an element, numbering from zero
grouping allows one list element to contain spaces
embedded quotes can preserve a nested multiword element
list structure depends on Tcl's grouping / escaping rules
6
string command: operations selected by its first argument
index: character at a zero-based position
range: substring between inclusive endpoints
end / end-1: final / penultimate position
length: number of characters
toupper / tolower: change case
trim / trimleft / trimright: remove surrounding whitespace
replace: replace a range of characters
equal / compare: compare strings, with different result formats
is: test a category, such as integer or alphabetic text
example: abrakadabra
index 4 -> k; range 4 6 -> kad; length -> 11
7
command-line arguments are available through built-in variables:
argc: argument count, excluding the script name
argv: list of arguments, excluding the script name
argv0: script name
these resemble C names but use a different counting convention
8
simple argument examples:
puts $argv: display the argument list
lindex $argv 0: retrieve the first argument
expr can evaluate that argument as an expression
the initial calculator lacks argument checks; next section fixes this
12.2.3 Branches, loops... and strings
Control constructs are commands receiving condition and body strings,
rather than special parser syntax. Braces defer substitutions so loops
can reevaluate changing values, and user-defined commands can build
similar control structures.
Detailed notes - 12.2.3: Branches, loops... and strings
1
the first calculator fails when called without arguments
expr receives an empty expression
interpreter diagnostics expose implementation details to the user
2
application behavior should be controlled by the application
detect user mistakes and respond deliberately
3
error messages should explain the problem in terms the user understands
the author contrasts this with the Lisp / Prolog systems tested
Tcl provides mechanisms for handling such errors in the script
4
first repair: check that argc is 1
true: evaluate the supplied expression and print the result
false: print usage instructions to stderr and exit with status 1
5
argument counting alone does not reject an invalid expression
catch runs expr and captures failure
success: print the computed result
failure: print an application-level message and exit unsuccessfully
6
if resembles a C branch superficially
comparison uses ==
braces around the condition need a different explanation
7
understanding that explanation matters more than copying familiar shapes
the author describes initially using Tcl without understanding it
8
braces delimit a string argument
they are not Tcl's version of a C compound statement
variable / command substitution is deferred in a braced word
literal newlines can remain inside that string
9
braces inside a braced word must balance
nested braces remain part of its text
an escaped brace is excluded from nesting counts
its backslash remains in the resulting braced text
backslash-newline is a special substitution even in braced words
10
double quotes allow escapes such as \n, \r and \t
braced text preserves these sequences at this evaluation stage
later evaluation of that text may interpret them
11
if is an ordinary built-in command
general command processing:
identify/group words, then substitute within each word
ordinary substitution does not split a word into new arguments
use the first word as the command name
pass the remaining words as arguments
let that command decide how to interpret its arguments
12
this model permits new control constructions
implemented in Tcl procedures or C commands
no change to the core parser is required
13
command names are not reserved language keywords
a procedure can replace an existing command name
rename can retain the old command under another name
replacing familiar controls is possible but can obscure a program
14
if receives the condition as string data
evaluates it using Tcl expression rules
uses the resulting boolean to choose a branch
15
boolean representations:
zero: false; nonzero numeric values: true
true / on / yes and false / off / no
accepted boolean words are case-insensitive
valid unambiguous abbreviations are also accepted
arbitrary strings are not automatically true
command and variable names remain case-sensitive
16
branch bodies are also string arguments, interpreted as scripts
only the selected script is executed
else is recognized by the if command's implementation
it is not a keyword understood by the core parser
17
then and else can be optional in supported if forms
if $b "puts YES" "puts NO": both bodies are ordinary strings
off selects NO; on selects YES
18
braces are convenient because they defer substitutions
#!/bin/sh
# calc1.tcl \
exec tclsh "$0" "$@"
if { $argc == 1 } {
set x [lindex $argv 0]
set code [catch { expr $x } result]
if { $code } {
puts stderr "Couldn't evaluate the expression ``$x''"
exit 1
} else {
puts $result
}
} else {
puts stderr "Please specify an arithmetic expression"
puts stderr "as the first parameter, such as"
puts stderr " $argv0 '2*2'"
exit 1
}
12.2.4 Procedures and variable visibility
proc defines a command with local parameters and a script body.
global accesses shared variables, upvar aliases another frame's
variable, and uplevel evaluates code in another context, supporting
control abstractions and operations such as swap.
Detailed notes - 12.2.4: Procedures and variable visibility
1
proc defines a new Tcl command implemented in Tcl
arguments: command name, parameter list, body
each argument is a string
an empty parameter list means no arguments are required
2
hello example: a procedure whose body prints Hello, world
braces conveniently quote the empty list and body
double-quoted strings with suitable escaping express the same data
3
parameter list gives both argument count and local parameter names
greet receives one name, which can contain spaces
return value:
return value: stop the procedure and return that value
otherwise: return the last executed command's result
quad can return x*x implicitly or through explicit return
args as the final formal parameter:
collect all remaining arguments into a list
supports a variable number of arguments
4
sumargs example:
initialize sum to zero and add every element of args
no arguments -> zero
maximum example:
require one ordinary argument, followed by args
initialize maximum from the required argument
compare remaining values; an empty-input maximum is avoided
variables inside procedures are local by default:
reading a same-named global does not find it automatically
assigning a local does not alter that global
global x y:
create local aliases for global variables x and y
a procedure can then read / change those globals
the example adds x and y; the author discourages global coupling
5
global can receive a name computed at runtime
first print_and_clear receives the name of a global variable
builds a command to read it, prints it, then assigns an empty string
nested quoting / eval makes this example unnecessarily awkward
it also cannot operate on an ordinary caller-local variable
6
upvar links a local name to a variable in the caller's context
arguments occur in external-name / local-alias pairs
supports an effect similar to a reference parameter
revised print_and_clear:
receive the variable's name
upvar $name var: create the alias var
print $var and set var to an empty string
works for both global callers and procedure-local callers
7
swap example:
receive two variable names and create aliases p and q
save p temporarily, assign q to p, assign the saved value to q
return an empty string; the useful result is the changed variables
#0: global frame; #1: first absolute procedure frame
deep frame dependencies make code fragile
9
uplevel evaluates a script in another frame
level notation follows upvar
remaining arguments are combined as script text
useful for implementing controls that run a caller-supplied body
for example, a loop with a postcondition
10
assignment creates a variable; unset removes it
info exists name: 1 if the variable exists, otherwise 0
other info subcommands inspect interpreter state
12.2.5 Handling exceptional situations
Every Tcl command completes with both a result and a control code for
success, error, return, break, or continue. catch captures that
completion, while surrounding procedure and loop contexts interpret or
propagate the code.
commands return values, but some also alter surrounding control flow
return: leave a procedure or an appropriate script context
break: leave a loop
continue: finish one loop iteration
2
error message: raise an error with a supplied message
unwind execution until a handler is found
otherwise the interpreter reports the error and its context
3
every Tcl command also has a completion code
0 / ok: normal completion
1 / error: error
2 / return: return from the relevant context
3 / break: leave a loop
4 / continue: continue a loop
additional numeric codes can support custom control mechanisms
4
ordinary script evaluation continues only after completion code 0
any other code stops the current sequence of commands
5
surrounding contexts decide what to do with the completion code
loops handle break / continue from their bodies
procedure and script contexts handle return
an unhandled error propagates outward
break / continue in inappropriate contexts become errors
6
return -code can specify how the procedure completes
numeric code or its recognized symbolic name
a procedure returning -code break can act as a custom break
similarly for continue
7
return -code return can return from the calling procedure
retABC returns with code 2 and value ABC
a caller invoking retABC consequently returns ABC
8
catch script resultVariable:
execute the supplied script and catch its completion
store its returned value / error message in the named variable
return the numeric completion code as catch's own result
9
suspicious 42 example:
capture code with set code [catch {...} result]
code 0: result contains the procedure's successful return value
code 1: result contains the error message
10
other completion codes remain possible
explicit return -code can generate them
intermediate procedure contexts may handle / transform them
11
inspect the code and report success or failure deliberately
separating catch from if can make the logic clearer
the discussion uses the classic two-argument catch interface
12.2.6 Files, streams and external commands
Tcl channels cover files, standard streams, pipelines, and sockets
with configurable blocking and encoding. Event callbacks support
nonblocking work, while bidirectional pipelines require careful
read-write ordering and closing to avoid waiting indefinitely.
Detailed notes - 12.2.6: Files, streams and external commands
1
Tcl I/O combines familiar file operations with command pipelines
open can open a file or start an external command
text is the natural interface; binary data need explicit care
2
open filename mode: open a channel
r: read; r+: read / write an existing file
w: write, creating or truncating; w+: read / write with truncation
a: append
binary mode avoids text transformations
3
mode can also be a list of low-level-style flags
RDONLY, WRONLY, RDWR, APPEND, CREAT, EXCL and others
{WRONLY CREAT TRUNC}: create / truncate for writing
4
optional permissions argument applies when creating a file
normally an octal mode such as 0666 or 0600
default creation mode is 0666, subject to the process umask
5
omitting mode opens the file for reading
open "file.txt": read
open "file.txt" "w": create / truncate for writing
text processing is the main use discussed here
6
open returns a channel identifier
save it for subsequent I/O and close
treat its textual spelling as opaque
standard channels: stdin, stdout and stderr
7
open can fail before an enclosing set executes
catch the operation and report its diagnostic appropriately
filename beginning with | requests a command pipeline:
read mode: read the command's captured output
write mode: send data to the command's input
examples: read an ls listing or feed a grep filter
8
a pipeline can be opened for both reading and writing
buffering can prevent an apparent line-by-line dialogue
flush affects our output, not the external program's buffers
pipe behavior differs from interactive terminal behavior
9
possible approaches include sending all input and closing the write side
nonblocking I/O is another, more involved approach
10
puts writes a string and normally appends a newline
-nonewline suppresses that newline
optional channel argument selects the destination
otherwise output goes to stdout
11
read and gets require an explicit channel
use stdin for standard input
12
gets reads one line, excluding its newline
one argument: return the line itself
second argument: store the line in that variable
return its character count, or -1 when no line is available
the variable form distinguishes an empty line from end-of-file
13
read channel ?count?: read characters
omitted count: read through end-of-file
reading stdin this way may wait for the user to signal EOF
an interactive interpreter shares that same standard input
14
blocking read with a count waits for that many characters or EOF
differs from a low-level read that may return currently ready data
nonblocking mode changes the waiting behavior
15
read returns the data as its result
it has no gets-style destination-variable argument
16
eof reports whether a previous read encountered end-of-file
test after attempting input
it does not predict the result of a future read
17
fblocked reports a previous nonblocking read's inability to get data
useful when distinguishing temporary unavailability from EOF
18
close releases a channel
closing a blocking command pipeline waits for its child commands
that wait must be considered when designing the interaction
the book criticizes limited process control at this interface
19
closing a nonblocking output channel may defer flushing
completion relies on the Tcl event loop running
returning from close does not necessarily mean all output was sent
20
an additional close direction can close only the read or write side
supported channel kinds include bidirectional command pipelines
socket half-close is related to shutdown
21
bidirectional command communication uses two underlying pipes
closing one direction closes the corresponding underlying path
22
remaining I/O facilities are introduced briefly
full option details belong to their reference documentation
23
fconfigure changes channel settings
blocking mode, text encoding, newline conversion and buffering
24
binary handles binary representations
format: construct binary data
scan: extract fields from binary data
encode / decode: textual forms such as base64, uuencode and hex
25
socket creates TCP clients or servers
server callback runs when a connection is accepted
it receives the new connection's channel
fileevent associates handlers with readable / writable channels vwait runs the event loop until a named variable changes
together these support an event-driven server
the script still needs a clear understanding of event ordering
26
file operates on filesystem objects and paths
copy, rename, delete and inspect files
query / change attributes and permissions
create directories and links
12.2.7 Associative arrays
Associative arrays map string keys to values and can be aliased
through upvar for procedure access. They are named variable collections
rather than first-class values; later dictionary facilities provide a
different value-oriented interface.
Detailed notes - 12.2.7: Associative arrays
1
lists can serve as ordinary integer-indexed sequences
lindex provides element access
cached internal list representations can make indexing efficient
2
these internal structures preserve the visible string / list semantics
their presence can be inferred from performance measurements
3
associative arrays map arbitrary string keys to values
suitable for sparse / named keys
dense numeric indexing is usually better represented by a list
4
array element syntax: arrayName(key)
set foo(bar,bur) value: assign one element
$foo(bar,bur): retrieve it
bar,bur is one string key, not two dimensions
5
key expressions can contain substitutions
$foo($a,$b): compute the key from a and b
a command result can also contribute to a key
constructed ordinary variable names are less convenient
creating m15 from m$i is easy
retrieving it needs another level of indirection
arrays have direct interpreter support for these operations
6
upvar can alias an entire array by name
arr receives array name a and key i
upvar $a an: local array alias
return $an($i): retrieve the selected element
7
array command provides whole-array operations
names: list keys
get: produce a key / value list
set: assign entries from such a list
further operations support searching and inspection
8
an array is not a first-class Tcl value
cannot be assigned or returned as one ordinary value
pass its name and use upvar to operate on it
alternatively serialize entries with array get
9
later Tcl versions provide dictionaries through dict
a dictionary is a value that can be passed / returned as a whole
retains a string representation with efficient internal storage
12.2.8 Comparing Tcl with Lisp
Both Tcl and Lisp can execute program-shaped data, but their default
evaluation conventions differ. Tcl explicitly requests substitutions in
text, while Lisp normally evaluates forms; passing Tcl code strings does
not itself create lexical closures.
Detailed notes - 12.2.8: Comparing Tcl with Lisp
1
shared ideas beneath different notation:
programs and data use the same representation
evaluation can execute constructed data
command / function calls identify an operation and its arguments
2
different defaults for evaluating data:
Lisp forms are normally evaluated; quotation suppresses evaluation
Tcl words remain text unless substitution is requested
$ requests a variable value; [...] requests a command result
3
Tcl control commands can receive unevaluated script strings
if and while use the ordinary command mechanism
users can build similar controls without special parser forms
the author regards this uniformity as conceptually simpler
4
Lisp functions can be first-class closures
preserve code together with its surrounding variable bindings
classic Tcl procedures are named associations of parameters and bodies
code strings themselves can be passed and returned as data
inserting values into a script can capture those values
this differs from retaining mutable lexical bindings in a closure
12.3 The Tcl interpreter and C
A C application can embed Tcl or expose existing C operations as new
Tcl commands. This supports a small scripting or GUI layer around
established components when the application has a concrete need for
extension.
Detailed notes - 12.3: The Tcl interpreter and C
1
Tcl was designed as an embeddable C library
tclsh is itself a user of that library
another C application can create and use an interpreter
2
the author recommends embedding only for a concrete requirement
knowing a technique does not make it necessary for every program
3
Tcl can also be extended with commands written in C
a short script can coordinate existing efficient components
the author favors this for modest tasks with acceptable overhead
4
example: a server needs configuration files created by its users
a small Tcl/Tk interface can help generate those files
the server itself need not acquire a graphical interface
5
reuse an existing C / C++ library for the file operations
a small adapter exposes its functions as Tcl commands
especially useful when the files have a binary format
6
the chapter explains the arrangement and a working example
detailed API reference material is needed when applying it
7
examples require Tcl library binaries and development headers
the book names tcl-dev for Debian-family distributions
12.3.1 Embedded Tcl
An embedded host creates an interpreter, collects complete commands,
evaluates them, and inspects results and completion codes. Registered C
callbacks add application operations, with client context and
result-lifetime rules forming part of the interface.
Detailed notes - 12.3.1: Embedded Tcl
1
minimal host program:
include the Tcl header
Tcl_CreateInterp: create an interpreter object
Tcl_Interp*: handle for commands, globals and evaluation state
2
Tcl_Eval executes command text and returns a completion code
/*
Tcl embedding/extending demo
Copyright (C) by Andrey Vikt. Stolyarov, 2019, 2025.
You can do whatever you want with this code; you're responsible
for any consequences.
To compile this as a Tcl interpreter:
gcc -Wall -g tclembed.c -ltcl -o tclembed
To compile this as a plugin for tclsh:
gcc -shared -fpic -Wall -g -DPLUGIN tclembed.c -o tclembed.so
The plugin can then be loaded from within tclsh with
load ./tclembed.so
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <tcl/tcl.h>
enum { maxcmd = 32 * 1024 };
static int read_command(char *cmd_buf, int bufsize)
{
int len = 0;
*cmd_buf = 0;
do {
const char *r;
if(len > bufsize-3) { /* nowhere to read "}\n" to */
fprintf(stderr, "Command too long\n");
return 0;
}
cmd_buf[bufsize-2] = 0;
r = fgets(cmd_buf + len, bufsize-len, stdin);
if(!r) /* EOF */
return 0;
if(cmd_buf[bufsize-2]) {
int c;
fprintf(stderr, "Command too long\n");
while((c = getchar()) != EOF && c != '\n')
{}
return 0;
}
len += strlen(cmd_buf+len);
} while(!Tcl_CommandComplete(cmd_buf));
return 1;
}
static void rep_loop(Tcl_Interp *interp, const char *prompt)
{
char *buf;
buf = malloc(maxcmd);
fputs(prompt, stdout);
while(read_command(buf, maxcmd)) {
int code;
const char *resptr;
Tcl_ResetResult(interp);
code = Tcl_Eval(interp, buf);
switch(code) {
case TCL_OK:
resptr = Tcl_GetStringResult(interp);
if(*resptr)
printf("%s\n", resptr);
break;
case TCL_ERROR:
resptr = Tcl_GetStringResult(interp);
fprintf(stderr, "TCL ERROR: %s\n", resptr);
break;
case TCL_RETURN:
fprintf(stderr, "return?! what's the hell?\n");
break;
case TCL_BREAK:
case TCL_CONTINUE:
fprintf(stderr,
"it's a bit strange to use break/continue this way\n");
break;
default:
fprintf(stderr, "unknown Tcl return code %d\n", code);
}
fputs(prompt, stdout);
}
}
static int
proc_triple(ClientData cd, Tcl_Interp *interp, int argc, const char **argv)
{
int len;
char *res;
if(argc != 2) {
Tcl_SetResult(interp, "must specify exactly 1 parameter", TCL_STATIC);
return TCL_ERROR;
}
len = strlen(argv[1]);
res = Tcl_Alloc(len*3+1);
strcpy(res, argv[1]);
strcpy(res+len, argv[1]);
strcpy(res+2*len, argv[1]);
Tcl_SetResult(interp, res, TCL_DYNAMIC);
return TCL_OK;
}
static int
proc_enter(ClientData cd, Tcl_Interp *interp, int argc, const char **argv)
{
const char *prompt = argc > 1 ? argv[1] : ">> ";
rep_loop(interp, prompt);
clearerr(stdin);
Tcl_SetResult(interp, "", TCL_STATIC);
return TCL_OK;
}
#ifndef PLUGIN
int main()
{
Tcl_Interp *interp = Tcl_CreateInterp();
Tcl_CreateCommand(interp, "triple", proc_triple, NULL, NULL);
Tcl_CreateCommand(interp, "ENTER", proc_enter, NULL, NULL);
rep_loop(interp, "> ");
return 0;
}
#else
int Tclembed_Init(Tcl_Interp *interp)
{
Tcl_CreateCommand(interp, "triple", proc_triple, NULL, NULL);
Tcl_CreateCommand(interp, "ENTER", proc_enter, NULL, NULL);
return TCL_OK;
}
#endif
12.3.2 Extending tclsh's command set
A shared library can extend tclsh through an initialization entry
point that registers C commands. The same callbacks used by an embedded
interpreter can therefore become a loadable extension without rebuilding
the interpreter.
Detailed notes - 12.3.2: Extending tclsh's command set
1
loadable C / C++ extensions add commands without rebuilding tclsh
compile the implementation into a shared library
load that library into a running interpreter
this kind of extension is commonly called a plugin
2
command callbacks use the same interface as embedded Tcl commands
include the supporting functions they depend on
3
the plugin needs an initialization entry point
example: tclembed.so -> Tclembed_Init
receives the interpreter pointer
registers commands with Tcl_CreateCommand
returns TCL_OK or TCL_ERROR
4
reuse triple and ENTER from the embedded-interpreter example
conditional compilation selects main or plugin initialization
define PLUGIN to build the plugin version
shared-library build options in the example:
-shared: produce a shared object
-fpic: generate position-independent code
-DPLUGIN: select the initialization function
5
load ./tclembed.so adds the commands to tclsh
triple foobar returns foobar three times
ENTER opens the nested REPL and returns on EOF
the example archive contains the combined implementation
12.4 Graphical interfaces with Tcl/Tk
Tk exposes widgets as named commands, with separate facilities for
layout, window management, and event scripts. Variable links and
resource options connect interface state and presentation to ordinary
Tcl data.
12.4.1 Tk and the wish interpreter
Tk creates widgets with hierarchical path names that also act as
commands for later operations. Creation and geometry management are
separate steps, and wish keeps servicing GUI events after initial script
execution finishes.
Detailed notes - 12.4.1: Tk and the wish interpreter
1
Tk builds graphical interfaces from widgets
can be loaded into Tcl or used from a C / C++ application
wish already includes Tk and handles window-related options
2
interactive wish creates an empty main window and a terminal prompt
commands can be tested immediately
rlwrap provides convenient input editing
3
-name sets the application's name and initial title
use a simple identifier for the application name
wm title sets the visible title independently
the application name also matters to resource configuration
4
. identifies the application's main window
wm title . "Another Title": change that window's title
5
geometry hierarchy: a widget can contain managed subordinate widgets
the containing widget determines their available display area
6
parent / child hierarchy is a separate relationship
often coincides with geometry containment, but need not
destroying a parent destroys its descendants
7
all widgets except the main window have a parent
even additional top-level windows belong to this hierarchy
widget paths reflect parentage:
.grp.btn1: btn1 under .grp under .
ancestors must exist; levels cannot be skipped
use lower-case initial letters for component names
8
widget-creation command is named after the widget type
button .bt -text "Press Me"
returns the widget's path, .bt
9
creating a widget does not itself display / position it
a geometry manager must arrange it
place .bt -x 10 -y 10: position its corner at those offsets
fixed positions are mainly useful for this first demonstration
10
each widget path is also a command for operating on that widget
cget: read an option
configure: change options that remain configurable
button example:
read -text and assign it to a Tcl variable
change the label to a longer two-line string
requested widget size grows to fit the new text
-padx / -pady adjust space around its contents
11
button-specific operations include:
flash: briefly change its visual state
invoke: perform its configured action
12
label is a passive text widget
pack .lab -side bottom -fill x: occupy the bottom across its width
configure -text changes the label just as for a button
text and newlines influence its requested height
13
the main window also supports a widget command
. configure -bg #ff0000: set its background
button -command stores a script to run when activated
initialize counter i to zero
callback increments i and changes .lab's text to its new value
braces defer the callback's substitutions until execution
14
wish can visualize another program's work
have the program emit Tcl/Tk commands into a pipe to wish
the book's Prolog example animates knight-tour search / backtracking
15
complete GUI script uses wish as its interpreter
shell wrapper passes the script, -name and command-line arguments
x11echo example:
set a window title
display argv0 and argv in a label
create an Ok button whose command is exit
pack label above button
16
the shell-wrapper technique permits multiple interpreter arguments
useful for supplying both -name and its value
17
argv0 / argv work as in tclsh scripts
wish extends Tcl with graphical facilities
18
finishing a wish script does not normally end the GUI application
initialization finishes, then the event loop handles interaction
windows remain until the application is closed
interactive mode runs the interface while commands are being entered
12.4.2 Interacting with the window manager
The window manager controls top-level presentation, while wm requests
titles, state changes, geometry, and resize limits. Some behavior
depends on the manager, and gridded resizing expresses dimensions in
application-defined cell units.
Detailed notes - 12.4.2: Interacting with the window manager
1
window manager controls decorations, movement and resizing
gridded windows resize in units of an internal cell grid
useful for terminal-style character cells
wm grid / -setgrid describe that arrangement
geometry and size constraints then use grid units
8
other wm operations depend partly on the window manager
consult the reference when a more specialized operation is needed
12.4.3 Basic widgets
Tk widgets combine creation options with command suboperations and
optional variable links. Checkbuttons hold independent state, radio
buttons share a variable with distinct values, and entry widgets expose
editable text, selection, and validation.
Detailed notes - 12.4.3: Basic widgets
1
Tk offers many widget types beyond windows, buttons and labels
checkbutton / radiobutton: boolean / alternative choices
entry / text: single-line / multiline text editing
frame / labelframe: grouping containers
listbox, menu, menubutton, message, scale
panedwindow, scrollbar and canvas
2
the book explains principles rather than every widget option
installed man pages describe individual widgets
example: man 3tk button
3
main interfaces: creation options and widget-command subcommands
cget / configure are shared operations
standard options are documented together in options
standard means shared semantics, not support by every widget
4
-text supplies text for widgets such as labels and buttons -textvariable links displayed text to a global variable
changing the variable changes the display
entry also updates that variable when the user edits the field
multiple widgets can consequently share synchronized text
5
Tcl variable tracing supports these update notifications
trace can observe variable reads / writes and other changes
related tracing facilities also help debugging
6
-relief controls the border's appearance
raised, sunken, solid, groove, ridge or flat
-borderwidth / -bd sets its thickness
groove / ridge need enough pixels to show their structure
-padx / -pady add space around supported widget contents
exact applicability depends on the widget and content type
7
passive widgets display information; active widgets accept interaction
buttons, entries and selection controls have configurable behavior
explicit event bindings can also make passive widgets respond
8
-state can disable or otherwise alter interaction
button: normal, active, disabled
entry: normal, disabled, readonly
readonly permits selection / copying but prevents editing
supported states differ by widget
9
button combines -text with a -command callback
flash changes appearance briefly
invoke activates the callback, unless the button is disabled
10
checkbutton represents a boolean choice
supports select, deselect and toggle
also supports configure, cget, flash and invoke
11
-variable links a checkbutton to its state variable
default off / on values are 0 / 1
-offvalue / -onvalue can replace those representations
reading the variable reveals the selected state
assigning the variable also updates the widget
12
checkbutton -command is optional
user activation first changes the linked variable
then runs the callback, which can inspect the new state
13
-indicatoron 0 gives a checkbutton the appearance of a latching button
changes presentation, preserving the underlying choice behavior
14
radiobutton chooses one alternative from a group
supports much of the checkbutton interface
toggle does not fit its one-of-many meaning
15
radiobutton grouping uses -variable together with -value
same group: same variable, different values
selecting a button assigns its value to the variable
every button updates according to whether that value matches
the widgets need no direct knowledge of each other
16
entry has a richer text-editing interface
use its text operations or linked variable for actual content
17
entry get returns the current text
delete first last removes an index range, excluding last
insert index text inserts before that position
indices start at zero; end is just after the final character
delete 0 end, then insert 0 text: replace the whole contents
insert as an index denotes the insertion cursor
18
entry also supports icursor and selection operations
a linked variable is often simpler for ordinary content access
19
entry's linking option is -textvariable
changing the field changes the variable
changing the variable changes the field
20
validation can constrain / inspect entry edits
-validatecommand / -vcmd supplies a checking script
-validate selects when checks run
possible triggers include edits and focus changes
21
other widgets follow related option / subcommand conventions
learn their specialized behavior from the reference as needed
Geometry managers express different layout models: place uses
coordinates, grid uses rows and columns, and pack consumes edge strips.
Resizing requires explicit policies; pack's expand changes allocated
space while fill changes the widget within it.
Detailed notes - 12.4.4: Position and size
1
GUI layout must address both initial arrangement and window resizing
these often consume much of interface implementation work
2
geometry manager arranges widgets inside a containing widget
controls positions and sizes when available space changes
geometry propagation can also resize the container to fit contents
3
place uses explicit coordinates or fractions of container dimensions
straightforward, but manual positioning scales poorly
4
grid arranges widgets in rows / columns
a widget may span a rectangular group of cells
requested widget sizes influence row heights and column widths
5
pack places widgets along edges of remaining space
convenient for quickly assembling many interfaces
frames can group controls and use a different layout internally
6
distance units:
bare numbers: pixels
c: centimeters; i: inches; m: millimeters
p: points, each 1/72 inch
7
place options for position:
-x / -y: explicit offsets
-relx / -rely: fractions of container width / height
8
place options for size:
omitted dimensions use the widget's requested size
-width / -height: explicit dimensions
-relwidth / -relheight: fractions of the container
9
-anchor selects which point is placed at the requested coordinates
nw by default: upper-left corner
n, s, e, w: side midpoints
ne, sw, se: other corners; center: center
10
top-centered label example:
-y 0 -relx 0.5 -anchor n
absolute and relative offsets can be combined
-x 20 -relx 0.5: 20 pixels right of the horizontal center
11
place forget stops managing a widget
info reports its layout configuration
slaves lists widgets managed inside a container
12
grid requires more concepts but suits substantial structured interfaces
13
the grid grows as rows / columns are used
it need not be allocated as a fixed-size matrix beforehand
14
grid positioning:
-row / -column: zero-based cell coordinates
-rowspan / -columnspan: number of occupied rows / columns
row-by-row shorthand can place several widgets at once
x: leave a cell empty
-: extend the previous widget across another column
^: extend the widget above into this row
15
demonstration helper m creates a square frame with a centered label
frame dimensions are convenient in pixels
label dimensions instead relate to text units
place centers each label inside its frame
16
mosaic example combines empty cells and horizontal / vertical spans
Close button occupies a two-by-two region near the bottom
by default, small widgets are centered in their allocated regions
-sticky controls alignment / stretching within that region
adjacent compass letters: align toward a corner
opposite letters: stretch along that dimension
nswe: fill the entire region
17
row / column sizes need resizing policies as well
rowconfigure / columnconfigure set weights
equal nonzero weights distribute extra space evenly
uniform groups keep grouped dimensions proportional
the example gives all rows and all columns equal weights
18
grid provides forget, info and slaves
remove hides a widget while retaining its layout settings
it can then be restored without repeating those settings
19
pack repeatedly allocates a strip of the remaining empty area
top / bottom strips take the remaining width
left / right strips take the remaining height
the requested widget size determines the other initial dimension
20
pack's main options:
-side: choose top, bottom, left or right
-fill: stretch the widget along x, y, both or neither
-expand: let its allocated region receive surplus space
fill changes the widget; expand changes the region available to it
21
spiral example:
five passes through top, left, bottom, right
create labels numbered 1 through 20
each expands and fills its assigned region
place a Close button in the remaining center
experiment with fill / expand and resize the window to see the difference
22
pack also supports forget, info and slaves
23
pack / grid normally propagate requested geometry to their containers
this can override a container's requested width / height
propagate container 0 disables that automatic sizing
the example then requests a 400 by 400 main window
managed labels expand inside that chosen initial size
Book examples (2 files) - 12.4.4: Position and size
#!/bin/sh
# packdemo.tcl // this program is hereby put into public domain
# The next line starts wish \
exec wish "$0" -name "pack_demo" "$@"
wm title . "tcl/tk pack demo"
. configure -height 300 -width 300
pack propagate . 0
set i 0
for { set n 0 } { $n < 5 } { incr n } {
foreach sd { top left bottom right } {
incr i
label .l$i -text $i -relief ridge -bd 3
pack .l$i -side $sd -fill both -expand 1
}
}
button .b -text Close -command exit -bd 4
pack .b -side left -expand 1 -fill both
bind . <Escape> exit
12.4.5 Fonts
Font specifications combine family, size, and style, while named
fonts share changeable settings across widgets. Reconfiguring a named
font updates all its users without editing every individual widget
option.
Detailed notes - 12.4.5: Fonts
1
font control selects size, typeface and emphasis
needed when defaults are too small or text needs differentiation
2
simple text widgets use a -font option for their displayed text
a single label does not assign different fonts to separate words
richer widgets such as text provide more detailed styling
3
one font specification is a list of family, size and optional styles
styles include bold, italic, underline and overstrike
Times, Helvetica and Courier are conventional portable family names
{Courier 20 italic}: 20-point italic monospaced text
4
named fonts provide shared, changeable configuration
font create: choose family, size, weight, slant and other properties
#!/bin/sh
# \
exec tclsh "$0" "$@"
set greek {
alpha beta gamma delta epsilon zeta eta
theta iota kappa lambda mu nu xi omicron
pi rho sigma tau upsilon phi chi psi omega
}
foreach { x y z } $greek {
puts "$x $y $z"
}
12.4.6 Event handling
bind associates scripts with physical or virtual events through a
widget's ordered binding tags. Event substitutions supply details, and
break can stop later handlers, so shortcut placement and propagation
affect the whole interface.
Detailed notes - 12.4.6: Event handling
1
-command is sufficient for many simple interfaces
wait for a button, then inspect the other controls and act
unexpected actions while the user edits text can be confusing
2
bind associates a script with an event
keyboard / mouse actions, focus or window changes
widget appearance, disappearance or destruction
application-defined virtual events
bindings can make even passive widgets respond
3
keyboard binding examples:
<KeyPress-Escape> or <Escape>: Escape key
<Control-Shift-F3>: F3 while Control and Shift are held
an ordinary printable character can be specified directly
avoid global letter shortcuts that interfere with text-entry fields
4
<Triple-ButtonPress-3>: triple press of mouse button 3
example changes a label after that action
Double and Quadruple also describe repeated events
5
virtual events use doubled angle brackets
bind . <<TimeToGo>> script: install a handler
event generate . <<TimeToGo>>: produce that event
bind's three arguments: target tag, event description, script
6
target can represent a widget, top-level window or group
top-level bindings normally apply through descendant bindtags
class tags group widgets of a particular type
all is a predefined broad tag
bindtags can attach custom tags to chosen widgets
7
these targets all operate through the widget's bindtag list
widget and top-level names are normally present as tags
tags can be removed, inserted or reordered
8
event description forms:
printable character
<physical-event-description>
<<virtual-event-name>>
physical event types include KeyPress / KeyRelease and ButtonPress
also ButtonRelease, Motion, MouseWheel, FocusIn / FocusOut
#!/bin/bash
# x11echo.tcl // this program is hereby put into public domain
# The next line starts wish \
exec wish "$0" -name "x11_echo" "$@"
wm title . "tcl/tk x11 echo demo"
label .lb -text "$argv0 $argv ($argc)" -padx 10 -pady 10
pack .lb -side top -fill x
button .ok -text "Ok" -command exit
pack .ok -side bottom -fill x
while { 1 == 1 } {}
12.4.7 Resources and localization
X resources can move labels and presentation defaults out of Tcl code
into hierarchical option files. Loading the selected UTF-8 resource file
before widget creation supports localization, with specific matches
overriding broader defaults.
Detailed notes - 12.4.7: Resources and localization
1
translated interface strings can be kept outside program code
Tcl's msgcat serves a message-catalog role similar to gettext
this section uses X resources as another way to supply labels
2
X resources associate hierarchical option names with string values
names / classes identify application, widgets and option
capitalized components designate classes
dots specify hierarchy; asterisks can match intervening levels
3
resource-file syntax: resourceName: value
a precise path configures one option of one nested widget
Fig*foreground: black supplies a broad foreground default
more specific matches can override general ones
4
the section leaves detailed resource matching to the reference material
focuses on translating Tcl/Tk interfaces
5
wish -name myprog supplies application name myprog and class Myprog
Myprog.lab.text: text for .lab
nested widget paths produce corresponding resource paths
wildcard patterns can share labels for similarly named controls
6
resources can set other options as well
example: label relief and border width
option add supplies resource defaults from the script itself
7
localization procedure:
remove explicit widget -text values
put the corresponding English resources in a .rc file
copy it and translate the values for another language
choose a file from command-line / environment settings
option readfile loads it before creating the widgets
8
the resource-reading interface discussed here expects UTF-8 text
ASCII-only files conceal encoding differences
translated non-ASCII text must use the expected encoding
9
if the source file uses another encoding, convert it before loading
iconv is one tool for that conversion
12.5 Execution strategies as paradigms
Execution strategy influences both programming techniques and
application delivery. The following discussion separates script roles,
runtime translation, reflection, and dependency management before
presenting the author's preferred boundaries between core code and
extensions.
12.5.1 What is a script?
The book defines scripts by their auxiliary role in controlling other
programs, rather than by a fixed language feature set. Shell automation,
office macros, and embedded extensions illustrate this role across
different execution arrangements.
Detailed notes - 12.5.1: What is a script?
1
earlier command-language features do not define all scripting
strings as universal data and external-command control are common
browser JavaScript and embedded Lisp dialects differ from that model
command languages can also be used for nonscripting applications
2
the kind of program must therefore be distinguished from its language
examine the roles called scripting in different environments
the author distinguishes author automation from imposed site behavior
his criticism of browser scripting is a viewpoint, not a definition
5
MUD / IRC clients provided event-driven scripts
examples: react to low health or a familiar person entering a channel
6
embedded languages can configure complex applications
used when plain configuration data are insufficient
if the embedded program becomes the main substantial application, calling it a small auxiliary script becomes less useful
7
embedded systems may use a custom language or an existing dialect
domain-specific language / DSL: tailored to a particular problem area
general-purpose language: intended for many problem areas
8
adding domain-specific commands raises a terminology question
is extended Tcl a new language or Tcl with an application API?
both descriptions can capture part of the arrangement
9
scripting is one family of application domains
domain-specific languages cover many other purposes too
10
the author's working definition: scripts control other programs
from outside through commands, or inside through an embedded API
occupy an auxiliary role relative to the controlled application
make little sense independently of that application
11
dependence alone does not determine that auxiliary role
an OS supports applications, despite their dependence on it
an interpreter can similarly serve a substantial main application
ask which component supplies the primary purpose / value
12.5.2 Ousterhout's dichotomy and its
opponents
Ousterhout's dichotomy separates efficient component implementation
from scripting that connects and extends components. Historical critics
challenged both Tcl's suitability and the division itself; high
abstraction, typing, and application scale do not form a universal
two-category map.
Detailed notes - 12.5.2: Ousterhout's dichotomy and its opponents
1
the author questions using originally auxiliary languages as the main implementation language of substantial applications
this is his design position, not a restriction of those languages
2
the historical discussion centers on Richard Stallman and John Ousterhout
3
Stallman's 1994 message argued against Tcl as a common extension language
wanted an extension language capable of substantial programming
criticized Tcl's data structures, numeric model and syntax
recommended Scheme with Tk access
4
the book also recounts contemporary GNU plans for different syntaxes
its comments on those projects describe the historical discussion
5
Ousterhout's reply advocated two complementary language roles
C / C++: complex internal data structures and efficient computation
Tcl: short scripts connecting and extending those components
easy learning and composition matter especially in the latter role
dropping into C handles work unsuited to Tcl
he had not intended Tcl for programs of tens of thousands of lines
expressed surprise that some large applications remained manageable
accepted that Tcl could improve while defending the two-language idea
6
his later scripting article formalized this distinction
system programming languages versus scripting languages
compared language level and degree of typing on two axes
the resulting separation became Ousterhout's dichotomy
7
the author notes counterexamples to a simple two-region picture
Haskell combines high abstraction with a strong type system
the diagram alone cannot establish a universal classification
8
critics argue that languages associated with scripting can also serve general-purpose programming successfully
large Tcl applications already appeared in Ousterhout's reply
9
language use can expand beyond its original domain
Perl: text processing to broader programs
JavaScript: browsers to servers and other applications
Lua, Ruby, PHP and Python also enter this discussion
10
the author's proposed explanation emphasizes ease of initial learning
small useful programs attract people with limited prior training
he associates this with later reuse outside the original task
11
he combines two possible biases:
familiar-tool bias: try the tool one already knows on new problems
first-language attachment: treat the first model learned as natural
a solution being possible does not by itself make its design suitable
12.5.3 What is interpretation?
Compilation and interpretation can coexist through bytecode, virtual
machines, or native compilation with runtime support. The author focuses
on deployment dependence as a spectrum, which differs from asking
whether compilation occurred or how quickly code runs.
Detailed notes - 12.5.3: What is interpretation?
1
the chapter asks how execution strategy affects programming habits
terminology must first be made explicit
2
compilation and interpretation can coexist
translate source into an intermediate representation
execute it using a virtual machine, possibly with further compilation
storing the representation separately is only one design difference
3
the Lisp implementations examined retain substantial runtime support
saved applications can therefore be much larger than their own code
the book criticizes this deployment cost
4
SBCL's machine-code compilation illustrates the terminology problem
code generation and the amount of runtime machinery are distinct
calling CPU execution interpretation does not resolve that distinction
raw speed comparisons also answer a different question
5
CPU execution speed may matter less than time spent waiting for I/O
therefore performance is not the chapter's sole concern
6
the author's concern is development machinery required during execution
runtime evaluation / reading of source can retain translator functions
those facilities were often designed with programmers in mind
7
initial working criterion used by the author:
source passed to a program that executes it: interpreted execution
translated executable requiring no translator: compiled execution
these are deployment-oriented definitions for this discussion
8
development and user environments may be different machines
ask which development tools the delivered program requires
processor microcode is outside this chosen distinction
9
the criterion remains imprecise
a runtime rarely needs every tool used during development
the programmer's text editor is an obvious counterexample
10
historical systems sometimes tied execution closely to their editor
earlier BASIC examples illustrated that arrangement
11
debuggers also raise a separation issue
an end user normally needs an application-level error response
the book's Common Lisp experiments exposed debugger-oriented behavior
12
bytecode execution needs runtime machinery even without its source compiler
the author groups this as partial interpretation for his argument
this differs from saying that no compilation occurred
13
libraries complicate the proposed boundary further
compiled C / C++ programs can require shared libraries
static linking instead includes needed library code in the executable
library use alone does not make ordinary C execution interpretation
14
platform-provided runtimes blur the distinction again
what users regard as part of the OS depends on the platform
the book discusses managed runtimes and mandatory platform APIs
15
final proposal: treat runtime dependence as a spectrum
more required development-system machinery -> more interpreted, in the author's specific sense
earlier assembly programs needed only the CPU and OS kernel
the C example without a standard library approached that arrangement
compiler-generated helper routines can still introduce dependencies
Reflection exposes program structure or execution as manipulable
data, and reification makes otherwise implicit machinery available
explicitly. Runtime replacement can then change behavior far from its
source definition, complicating debugging and other components'
assumptions.
Detailed notes - 12.5.4: Interpretation as a paradigm
1
available runtime source / translator facilities invite new uses
eval is one example: execute code constructed during execution
2
a program controls its interpreter only through exposed facilities
some capabilities may be absent or intentionally inaccessible
3
Hopeless example:
top-level directives define / inspect functions and types
write can output elements of an unbounded lazy list incrementally
those directives are not expressions callable from Hope functions
4
other systems expose much more of their execution machinery
inspect names and definitions
replace program components during execution
alter parts of the evaluator's behavior
5
reflection: access to a program's own structure or execution
structural reflection: inspect / modify internal program objects
behavioral reflection: influence the evaluation process / context
the book introduces this through Brian Smith's account
6
reification makes otherwise implicit machinery available as program data
provide objects representing it and operations on those objects
7
a closure can normally be used without exposing its internals
behavior reveals captured bindings
does not necessarily permit reading / changing its stored body
the book treats the examined closures as black boxes
8
hypothetical closure-inspection operations would reify those internals
retrieve / replace body
list captured variables and inspect / alter their bindings
implementation becomes more constrained by the exposed representation
9
textual program representation is easy to expose as ordinary strings
access / replacement operations can manipulate whole procedures
Lisp symbol names are an example of reified information
symbol -> string name; name -> existing or newly created symbol
the author questions whether such exposure is always beneficial
11
structural reflection is not confined to source interpreters
managed compiled languages expose metadata too
C dynamic loading can also involve looking up functions by name
12
continuations provide an example related to behavioral reflection
represent aspects of the current computation as usable objects
deeper reflective systems can expose interpreter data structures
program and interpreter updates may interfere
reflective towers separate levels to address that interference
the author questions the practical motivation of these constructions
13
the discussion then moves from theoretical machinery to practical risks
14
runtime patching replaces program behavior while it is running
the source definition a reader knows may no longer be the active one
15
this can obstruct debugging
reasoning from an unchanged-looking source definition becomes wrong
an unexpected replacement may be far from the observed failure
16
monkey patching can replace library behavior at runtime
documentation may no longer describe the modified behavior
one subsystem's patch can violate another subsystem's assumptions
17
the author strongly discourages everyday reliance on such patching
his concern is hidden behavioral change and difficult coordination
18
bytecode distribution can separate source translation from execution
reflection can remain available
generating new source is less direct if no source compiler is present
exact capabilities depend on the runtime, not this category alone
19
the broader recommendation is to separate developer concerns from user ones
programming mistakes and anticipated operating failures deserve appropriate, deliberately designed handling
12.5.5 Dependencies and self-contained
programs
Build-time and runtime dependencies create different delivery
obligations, and transitive requirements form a graph. Static linking,
bundled runtimes, package managers, and containers address parts of that
problem while carrying their own maintenance and distribution costs.
Detailed notes - 12.5.5: Dependencies and self-contained programs
1
interpretation costs can include startup translation as well as execution
caching and incremental translation can reduce those costs
performance is only one aspect of the author's objection
2
dependency: something required for another component to function
the book compares battery-powered and mechanical watches
3
self-contained describes independence from additional required components
its meaning differs from autonomous behavior
4
software always depends on some underlying platform
the chapter treats CPU / OS requirements as the baseline
self-contained here means avoiding extra dependencies above it
5
build-time dependencies are needed to produce the delivered program
compiler, build tools, headers and libraries
runtime dependencies are needed to execute the delivered program
shared libraries, data files, images and external commands
6
transitive dependencies form a directed graph
package managers track and install required packages automatically
manual tracking quickly becomes difficult
7
ship analogy used by the author:
pumps can compensate for leaks, but encourage neglect if treated as a reason to stop sealing the hull
larger compensating mechanisms can hide a worsening basic design
8
he asks the reader to explain why that engineering approach is unsound
merely calling it obviously wrong does not identify the principle
9
principle: having a solution to a problem is not a reason to create it
every workaround has costs
treating manageable problems as nonexistent can allow them to grow
10
historical example from the author's machine: installing Atril proposed many packages and substantial downloads
some dependencies were real; others followed packaging choices
this is an anecdote about that installation, not a current size claim
11
updating one shared dependency can require coordinated upgrades
further dependencies may extend the update through the system
new versions can also introduce regressions or remove useful behavior
12
incompatible version requirements create dependency conflicts
the author calls the resulting difficulty dependency hell
his claim of inevitability is part of the argument
13
maintainers also inherit developers' dependency choices
obtaining and building prerequisites can dominate packaging work
each additional component requires maintenance effort
14
the author's preferred delivery models:
user: copy one executable, run it, remove it when finished
maintainer: unpack a source tree and build with supplied prerequisites
15
bundled source and static linking can approach these ideals
include required library sources and needed code in the executable
an externally supplied interpreter remains an additional dependency
16
a compact bundled interpreter could also simplify delivery
the author argues that larger surrounding ecosystems often obstruct it
17
interpreter ecosystems may require extra installers and language libraries
convenience for developers can transfer setup work to users
the relevant cost is the complete deployed environment
18
a package-manager command may automate installation
the author argues that automation does not remove all resulting costs
19
less common target platforms may lack ready-made runtime packages
users may need to build prerequisites themselves
expertise does not make that work free
20
author's Openwall example:
an unsuccessful Erlang build influenced his Jabber-server choice
illustrates a deployment constraint on that particular environment
21
availability of installation tools differs across systems
the book's platform examples reflect its historical experience
a solution available on one system cannot simply be assumed elsewhere
22
several applications sharing an ecosystem may require conflicting versions
A common abstraction can hide platform differences while omitting
needed capabilities or fitting some systems poorly. Portability
therefore depends on actual application requirements and on the runtime
itself being available and tested on each target.
Detailed notes - 12.5.6: The portability myth
1
higher-level abstractions can hide platform differences
this does not by itself guarantee effortless portability
2
platforms expose different underlying facilities and conventions
process creation, readiness notification and graphical interfaces
equivalent-looking APIs may have different limits or costs
3
a common abstraction can fit some platforms poorly
the author criticizes environments that impose an awkward model
a portable interface still needs suitable platform implementations
4
an abstraction may omit a needed platform capability
extensions / foreign interfaces can fill the gap
platform-specific use then requires additional portability work
absence from Common Lisp's standard is not absence from every library
5
runtimes themselves are software that must be ported and tested
complex applications can reveal differences missed by small examples
6
the author favors planning portability around actual application needs
implement the required common interface over each platform
gives C / C++ and a portable widget library as his preferred approach
7
his Tcl/Tk versus C++ comparison reflects his own deployment experience
include installation burden in portability planning
do not treat that experience as a universal language ranking
12.5.7 When interpretation is appropriate
Interpretation can suit personal automation, controlled environments,
appliances, and user extension languages. The author's two-layer model
keeps essential maintained behavior in the compiled core, with
user-modifiable scripts calling its operations through a clear
boundary.
Detailed notes - 12.5.7: When interpretation is appropriate
1
the criticism raises a question: why study these interpreted languages?
2
alternative paradigms are useful intellectual tools
ideas can be valuable even without adopting a particular runtime
restricting dynamic facilities can make compact compilation easier
a language's possible implementations need not match one example
3
personal / short-lived programs avoid some deployment concerns
programmer and user are the same person
an existing interpreter may be entirely acceptable
examples: one-off runs and private task automation
4
internal organizational software can be considered similarly
development and operations costs fall within the same organization
the organization can choose a tradeoff that suits its needs
5
an appliance can hide its implementation environment from users
supplier installs and supports the complete software / hardware system
users need not manage the runtime themselves
6
domain-specific languages are another suitable use
scripting can control an existing application from inside or outside
more substantial domain programs may use an embedded interpreter too
scripting is one subset of this broader case
7
two layers have different modification expectations
main application: supplied by its developers
extension layer: intended for users to write / adapt
user code may be supplied initially or added later
8
this extends the two-language idea behind Ousterhout's dichotomy
users and application developers can have different skills / tasks
their languages can therefore have different design priorities
9
an embedded language can be simpler than the main implementation language
users avoid learning C++ and installing its full toolchain
a compact interpreter can expose the needed application operations
10
embedding the interpreter inside the main executable can simplify delivery
the user-facing extension environment becomes part of the application
11
keep any extension ecosystem focused on users' tasks
preserve the distinction between user tools and developer tools
12
the author proposes a two-layer paradigm
compiled application core
interpreted user-modifiable extensions
distinguishes roles, not merely performance-sensitive code
13
his architectural rule: core functionality must not depend on a particular
user-modifiable script remaining unchanged
extensions call core operations
essential implementation belongs in the maintained core
14
reason: users expect the extension layer to be safe to modify
hidden core assumptions about exact script contents violate that model
comments alone do not repair an unclear boundary
15
the author recognizes that his list of suitable cases may be incomplete
nevertheless argues strongly against transferring runtime-management burdens to an unknown public audience
this is his deployment philosophy, not a general prohibition
16
if future public distribution is plausible, he recommends considering compiled, statically linked delivery from the beginning
12.5.8 (*) Reflections on pure compilation
The author's proposed "pure compilation" combines no runtime
translation with explicit control over support libraries and delivered
artifacts. It also seeks identifier-renaming stability and build-time
computation, making this a language-design proposal rather than standard
terminology.
Detailed notes - 12.5.8: (*) Reflections on pure compilation
1
the author contrasts reflection research with his interest in reducing runtime development machinery
reports difficulty finding related work during his group's search
2
proposed ideal: implementation choices should not unnecessarily affect what an end user must see or manage
3
first requirement: no translator needed to run the delivered program
stronger form: no program translation during execution at all
installation should leave it ready to execute
4
bundling an interpreter with program text does not meet the stronger form
one executable file can still perform runtime translation internally
5
further requirements proposed by the author:
no mandatory external development-system components
include only explicitly requested libraries
allow the required library set to be empty
move substantial supporting mechanisms into optional libraries
6
implementation names should not change user-visible behavior
consistently rename identifiers without changing bindings
the author calls this stability under alpha conversion
7
ordinary C compilation may generate helper-library calls
operations unsupported directly by a target CPU need implementation
gcc can also assume certain memory-support routines exist
source with no explicit library calls can still require helpers
8
C macro stringification can expose an identifier's spelling
#x converts the argument token sequence into a string
renaming myvar then changes a printed string produced from its name
this violates the author's stated naming-independence requirement
9
another proposed requirement concerns compile-time computation
permit work whose inputs are known at build time to happen then
avoid forcing it into every execution
discusses format processing and compile-time function evaluation
cites D as an example supporting such evaluation
10
two further proposed controls over the delivered artifact:
avoid unnecessary traces of the particular implementation tool
permit producing any valid executable for the chosen target
the author uses assemblers as the point of comparison
11
he names the combined ideal pure compilation
a particular research / design proposal, not the usual definition
argues for a high-level language designed around those requirements
12
C++ demonstrates that low-level access can coexist with high abstractions
the author objects to mandatory support machinery for some features
discusses virtual dispatch, exceptions, allocation and RTTI
his criterion is optionality / control over implementation support
13
proposal: move such mechanisms into explicitly selected libraries
retain expressive abstractions with a minimal language core
choose different supporting libraries for different problem domains
14
the author presents pure compilation as a possible direction for a new general-purpose language, motivated by his criticisms of C and C++
Comments