GNU TeXmacsUser manualReferenceAboutEnglish
The evaluator

1.Evaluation of trees

tree edit_env_rep::exec (tree t)
(evaluate a tree in the current environment)

Returns the value of t. Strings evaluate to themselves. For compound trees, exec dispatches on the label (

Typeset/Env/env_exec.cpp

). Environment primitives, macro primitives, control structures, computational primitives, length units, graphical and animation primitives all have their own exec_* method. The result is a new tree without source location. Errors are not signalled by exceptions but returned as trees of the form (error "message") (label _ERROR), which the typesetter displays as source code in error style (concater_rep::typeset_error applies (rewrite-inactive (arg "x") "error") to it).

The end of the dispatch shows how the remaining tags are handled:

default:
  if (L(t) < START_EXTENSIONS) {
    int i, n= N(t);
    tree r (t, n);
    for (i=0; i<n; i++) r[i]= exec (t[i]);
    return r;
  }
  else return exec_compound (t);

Built-in tags without special semantics for the evaluator (typesetting primitives like concat, frac or document) are evaluated componentwise, while all user tags, whose labels are allocated dynamically above START_EXTENSIONS, are macro applications. A few built-in tags are also treated as macro applications by name: hlink, action, active, inactive, style-only and their variants are dispatched to exec_compound, because they are actually implemented as macros in the default environment (see initialize_default_env, which for instance defines inactive as (macro "body" (rewrite-inactive (arg "body") "once")) and include as (macro "name" (include* (arg "name")))). Some primitives only evaluate part of their arguments: macro and xmacro are returned as copies, quote returns its argument unevaluated, and move, shift, resize and clipped only evaluate their first argument.

exec_string (t) is a shortcut which returns the label of the result, or the empty string if the result is compound.

2.Macro application

A macro application (f a1 … am) (or (compound f' a1 … am), where f' is evaluated to obtain the name or the macro itself) is evaluated by exec_compound:

tree
edit_env_rep::exec_compound (tree t) {
  int d; tree f;
  if (L(t) == COMPOUND) {
    d= 1;
    f= t[0];
    if (is_compound (f)) f= exec (f);
    if (is_atomic (f)) {
      string var= f->label;
      if (!provides (var)) return tree (_ERROR, "compound " * var);
      f= read (var);
    }
  }
  else {
    string var= as_string (L(t));
    if (!provides (var)) return tree (_ERROR, "compound " * var);
    d= 0;
    f= read (var);
  }
  if (is_applicable (f)) {
    int i, n=N(f)-1, m=N(t)-d;
    macro_arg= list<hashmap<string,tree> > (
      hashmap<string,tree> (UNINIT), macro_arg);
    macro_src= list<hashmap<string,path> > (
      hashmap<string,path> (path (DECORATION)), macro_src);
    if (L(f) == XMACRO) {
      if (is_atomic (f[0]))
        macro_arg->item (f[0]->label)= t;
    }
    else for (i=0; i<n; i++)
      if (is_atomic (f[i])) {
        tree st= i<m? t[i+d]: tree (UNINIT);
        macro_arg->item (f[i]->label)= st;
        macro_src->item (f[i]->label)= obtain_ip (st);
      }
    tree r= exec (f[n]);
    macro_arg= macro_arg->next;
    macro_src= macro_src->next;
    return r;
  }
  else return exec (f);
}

The points to remember are:

3.Accessing arguments

tree exec_arg (tree t)
(the arg primitive)

For (arg "x" i1 … ik), looks up x in the innermost frame only (an error arg x is returned if it is not bound there), descends into the children with the evaluated indices i1, …, ik, and evaluates the resulting subtree. Crucially, the frame is popped while the argument is evaluated, and pushed back afterwards:

r= macro_arg->item [r->label];
list<hashmap<string,tree> > old_var= macro_arg;
list<hashmap<string,path> > old_src= macro_src;
if (!is_nil (macro_arg)) macro_arg= macro_arg->next;
if (!is_nil (macro_src)) macro_src= macro_src->next;
…
else r= exec (r);
macro_arg= old_var;
macro_src= old_src;

The argument tree comes from the caller, so any arg it contains refers to the parameters of the caller. This is what makes nested macro calls such as (macro "x" (strong (arg "x"))) work: when strong in turn evaluates its own (arg "body"), the arg of the outer macro is found one frame further down.

tree exec_quote_arg (tree t)
(the quote-arg primitive)

Like arg, but returns the argument tree without evaluating it. The returned tree is the argument tree as it was bound in the frame, not a copy. During typesetting this is the very subtree of the document, so it still carries its inverse path; this is important for extern (see below). When the static flag quote_substitute is set (during exec_until_quasi), the result is instead a tree whose children are arg references to the children of the argument.

tree exec_value (tree t)

tree exec_quote_value (tree t)

tree exec_or_value (tree t)
(reading variables)

value evaluates its argument to a name and returns the evaluated value of that variable; quote-value returns the value unevaluated; or-value returns the value of the first of its arguments which is defined and not UNINIT. Since stored values may themselves be expressions (for instance a length like (plus "1fn" (value "par-sep"))), value may trigger further evaluation.

get-label and get-arity evaluate their argument and return its label, respectively its arity; provides tests whether a variable is defined.

4.Environment primitives

tree exec_with (tree t)
(local variables)

Evaluates all variable names and new values before changing anything, then writes the new values, evaluates the body and restores the old values. The result is (with var1 (quote val1) … body'), where body' is the evaluated body: the evaluated values are wrapped in quote so that the result can safely be evaluated again.

tree exec_assign (tree t)
(global assignment)

Evaluates the name, then calls assign, which evaluates the value and stores it. Note that a macro evaluates to (a copy of) itself, which is why (assign "foo" (macro …)) stores the macro unevaluated. The result is (assign var val), again with quote around compound values other than macros. provide does the same, except when the variable is already defined.

The table formatting primitives (tformat, dlines, datoms, dpages) are also environment primitives: they append their formatting arguments to the corresponding variable (CELL_FORMAT, LINE_DECORATIONS, …) while the last argument is evaluated (exec_formatting). See environment primitives for the user-level description.

5.Evaluation control

The primitives eval, quote, quasiquote, unquote, unquote*, quasi and copy (see evaluation control primitives) are implemented directly in exec:

eval

exec (exec (t[0])): evaluates the argument and then evaluates the result once more.

quote

Returns t[0] unevaluated.

quasiquote

Calls exec_quasiquoted, which copies the tree while replacing each (unquote u) by the value of u and splicing in the children of the value of each (unquote* u).

quasi

Evaluates the result of quasiquote once more; this is the idiomatic way to build a tree with computed parts and then evaluate (or typeset) it.

The control structures if, case, while and for-each (exec_if, exec_case, …) require their conditions to evaluate to the strings true or false; anything else yields an error tree. while returns the concat of the values of its body, whereas for-each applies a macro to each element of a tuple only for its side effects and returns the empty string.

6.Rewriting

tree edit_env_rep::rewrite (tree t)
(one rewriting step)

Transforms a tree with one of the labels EXTERN, MAP_ARGS, VAR_INCLUDE, WITH_PACKAGE or REWRITE_INACTIVE into another tree, and returns other trees unchanged. exec_rewrite (t) is simply exec (rewrite (t)); the typesetter instead typesets the rewritten tree (concater_rep::typeset_rewrite, bridge_rewrite_rep). Rewriting is not memoized: each time a rewritable tree is evaluated or typeset, rewrite is called again.

The cases are:

map-args

(map-args f g x start end) builds a tree with label g whose children are (f (arg x i) i) for i between start and end (or just (arg x i) if f is identity). Note that the result contains arg references to the children of the argument, not copies of these children. When the result is typeset, these references are resolved by the typesetter, which therefore knows the source location of each child and keeps them editable.

include*

(label VAR_INCLUDE, produced by the include macro) loads the document with load_inclusion, relative to base_file_name.

with-package

See the typesetting environment.

rewrite-inactive

Produces the source code rendering of an argument (rewrite_inactive in

Typeset/Env/env_inactive.cpp

). This is how inactive tags, the preamble and style files are displayed. The rendering is built from arg references with index paths (the function subvar appends an index to the current arg reference) and mark tags, so that the displayed source remains editable.

extern

Calls Scheme; see the next section.

7.The extern primitive and Scheme macros

(extern f a1 … an) applies the Scheme function f to the trees a1, …, an and returns the result, converted back to a tree. The implementation is the EXTERN case of rewrite:

string fun= tm_decode(exec_string (t[0]));
tree r (TUPLE, n);
for (i=1; i<n; i++)
  r[i]= exec (t[i]);
object expr= null_object ();
for (i=n-1; i>0; i--)
  expr= cons (object (r[i]), expr);
expr= cons (string_to_object (fun), expr);
if (!secure && script_status < 2) {
  if (!as_bool (call ("secure?", expr)))
    return tree (_ERROR, "insecure script");
}
edit_env old_env= current_rewrite_env;
current_rewrite_env= edit_env (this);
object o= eval (expr);
current_rewrite_env= old_env;
return content_to_tree (o);

Several details matter in practice:

tm-define-macro is unrelated to markup macros: it defines Scheme macros in the same way as tm-define defines functions. There is no ext primitive; the prefix ext- is only a naming convention for Scheme functions meant to be called through extern.

8.Partial evaluation: exec_until

The environment at a given position inside a tree is computed by partial evaluation, which performs all side effects of the part of the tree which precedes the position, and the environment changes of the constructs which enclose it.

void exec_until (tree t, path p)
(execute t up to the position p)

p is a tree path inside t in the usual sense: the last item is a position (0 or 1 for a compound tree, a character index for a string). If p is atomic and nonzero, the whole of t is executed. For a with, the new values are written with monitored_write_update and the evaluation continues inside the body without restoring anything; for a tformat or table the cell format is updated; for other built-in tags, all children before p->item are executed for their side effects and the recursion continues in child p->item. Macro applications are handled by exec_until_compound (t, p).

Positions inside the argument of a macro are the difficult case, since the argument is not part of the macro body: the body contains (arg "x"), possibly deep inside other constructs or even inside other macro calls. exec_until_compound (t, p) determines the name var of the parameter which corresponds to child p->item, pushes a frame of arguments and calls the second form of exec_until:

bool exec_until (tree t, path p, string var, int level)
(search for an argument)

Traverses t in evaluation order, executing everything it meets, until it finds the place where the argument var is used; then it continues with exec_until (arg, p) inside the actual argument and returns true. If it is not found, false is returned and with changes made on the way are undone.

The parameter level counts how many macro frames lie between the current frame and the one in which var is bound. exec_until_compound (t, p, var, level) pushes a frame and recurses with level+1; exec_until_arg (t, p, var, level) pops a frame and, if level is zero and the parameter name is var, has found the target (taking into account index paths such as (arg "x" "1")); otherwise it recurses into the argument with level-1. exec_until_mark handles mark, which is used to indicate that a subtree represents a given argument for cursor positions on its border.

Rewritable primitives are handled by applying rewrite and searching the result (exec_until_rewrite); quasi is handled by exec_until_quasi, which sets quote_substitute so that quoted arguments are replaced by arg references which can be searched. The bridges have their own my_exec_until methods, which reuse cached environment changes when possible (see bridge_rep::exec_until and bridge_with_rep::my_exec_until).

9.Expansion and dependency tests

tree expand (tree t, bool search_accessible= false)
(substitute arguments)

Replaces arg and quote-arg references in t by the corresponding argument trees (recursively expanding arg through the frames, but without evaluating anything else) and expand-as by its first argument. With search_accessible set, it instead returns the first subtree which is accessible, that is, which has a valid inverse path in the document and is an accessible child according to the DRD. This is used by find-accessible (exec_find_accessible), hard-id (exec_hard_id), build_locus and concater_rep::typeset_set_binding to find the part of the document which is represented by a macro argument.

bool depends (tree t, string s, int level)
(does a tree depend on an argument?)

Tests whether t refers, directly (level zero) or through level intermediate macro frames, to the parameter s via arg, quote-arg, map-args or eval-args. The bridges use it to decide whether a modification of a macro argument invalidates them. As the FIXME in the code says, dependencies created by rewriting (for instance through extern) are not detected.

Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.1 or any later version published by the Free Software Foundation; with no Invariant Sections, with no Front-Cover Texts, and with no Back-Cover Texts. A copy of the license is included in the section entitled "GNU Free Documentation License".