![]() |
The evaluator | ![]() |
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.
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:
The value of the tag name is looked up in the environment at the moment of the application (dynamic binding), and is_applicable accepts macro, xmacro and func trees.
A new frame is pushed on macro_arg and macro_src. For a macro with parameters x1, …, xn, the parameter xi is bound to the unevaluated argument tree (call by name). Missing arguments are bound to UNINIT; extra arguments are ignored. For an xmacro the single parameter is bound to the whole application t, so that (arg "x" "i") designates the i-th child.
The body is evaluated, and the frame is popped again.
If the value of the tag is not a macro, the value itself is evaluated. Thus a variable can be used as a tag without arguments: foo evaluates to the value of the variable foo.
If the tag is not defined at all, the result is an error tree compound foo.
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.
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)
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.
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.
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.
The primitives eval, quote, quasiquote, unquote, unquote*, quasi and copy (see evaluation control primitives) are implemented directly in exec:
exec (exec (t[0])): evaluates the argument and then evaluates the result once more.
Returns t[0] unevaluated.
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).
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.
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 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.
(label VAR_INCLUDE, produced by the include macro) loads the document with load_inclusion, relative to base_file_name.
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.
Calls Scheme; see the next section.
(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:
The first argument is evaluated and parsed as Scheme code; it can be a function name such as ext-hello or a whole lambda expression.
The arguments are evaluated with exec before they are passed. With (arg "x"), Scheme receives a fresh, evaluated copy of the argument without source location; if it is inserted into the result, it will be typeset as a non-editable decoration. With (quote-arg "x"), Scheme receives the original subtree of the document, and if the function returns it (or one of its subtrees) unchanged inside its result, the typesetter recognizes its inverse path and the user can edit it. The demonstration package
packages/example/extern-demo.ts
uses this idiom:
<assign|hello|<macro|body|<extern|ext-hello|<quote-arg|body>>>> |
with, in
utils/misc/extern-demo.scm
,
(tm-define (ext-hello t)
(:secure #t)
‘(concat "Hello " ,t "!")) |
Unless the document is trusted (secure, determined by is_secure from the file name) or the user accepted all scripts (script_status is 2), the expression is first checked by the Scheme predicate secure? (
kernel/texmacs/tm-secure.scm
). A function passes this check if it has the property :secure, which is set by the (:secure #t) option of tm-define or by define-secure-symbols. Otherwise the result is the error insecure script.
While the Scheme function runs, the static variable current_rewrite_env points to the environment. The function texmacs_exec (the Scheme primitive texmacs-exec) uses this environment when it is set, so that Scheme code called from extern can evaluate markup in the environment of the macro application. The old value is saved and restored, which makes the mechanism re-entrant.
The result is converted with content_to_tree, and it is evaluated (by exec_rewrite) or typeset, so it may itself contain macro applications.
By default, the children of extern are not accessible for the DRD. A style can declare accessibility for a particular function f through the pseudo tag extern:f, as in
packages/customize/math/math-check.ts
:
<drd-props|extern:math-check|with-like|true|arity|1|accessible|all|regular|all> |
(see drd_info_rep::is_accessible_child).
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.
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.
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:
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).
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.
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.