texmainbody.c /size: 29 Kb    last modification: 2025-02-21 11:03
1/*
2    See license.txt in the root of this project.
3*/
4
5# include "luametatex.h"
6
7/*tex
8
9    This is where the action starts. We're speaking of \LUATEX, a continuation of \PDFTEX\ (which
10    included \ETEX) and \ALEPH. As \TEX, \LUATEX\ is a document compiler intended to simplify high
11    quality typesetting for many of the world's languages. It is an extension of D.E. Knuth's \TEX,
12    which was designed essentially for the typesetting of languages using the Latin alphabet.
13    Although it is a direct decendant of \TEX, and therefore mostly compatible, there are some
14    subtle differences that relate to \UNICODE\ support and \OPENTYPE\ math.
15
16    The \ALEPH\ subsystem loosens many of the restrictions imposed by~\TeX: register numbers are no
17    longer limited to 8~bits. Fonts may have more than 256~characters, more than 256~fonts may be
18    used, etc. We use a similar model. We also borrowed the directional model but have upgraded it a
19    bit as well as integrated it more tightly.
20
21    This program is directly derived from Donald E. Knuth's \TEX; the change history which follows
22    and the reward offered for finders of bugs refer specifically to \TEX; they should not be taken
23    as referring to \LUATEX, \PDFTEX, nor \ETEX, although the change history is relevant in that it
24    demonstrates the evolutionary path followed. This program is not \TEX; that name is reserved
25    strictly for the program which is the creation and sole responsibility of Professor Knuth.
26
27    \starttyping
28    % Version 0 was released in September 1982 after it passed a variety of tests.
29    % Version 1 was released in November 1983 after thorough testing.
30    % Version 1.1 fixed "disappearing font identifiers" et alia (July 1984).
31    % Version 1.2 allowed '0' in response to an error, et alia (October 1984).
32    % Version 1.3 made memory allocation more flexible and local (November 1984).
33    % Version 1.4 fixed accents right after line breaks, et alia (April 1985).
34    % Version 1.5 fixed \the\toks after other expansion in \edefs (August 1985).
35    % Version 2.0 (almost identical to 1.5) corresponds to "Volume B" (April 1986).
36    % Version 2.1 corrected anomalies in discretionary breaks (January 1987).
37    % Version 2.2 corrected "(Please type...)" with null \endlinechar (April 1987).
38    % Version 2.3 avoided incomplete page in premature termination (August 1987).
39    % Version 2.4 fixed \noaligned rules in indented displays (August 1987).
40    % Version 2.5 saved cur_order when expanding tokens (September 1987).
41    % Version 2.6 added 10sp slop when shipping leaders (November 1987).
42    % Version 2.7 improved rounding of negative-width characters (November 1987).
43    % Version 2.8 fixed weird bug if no \patterns are used (December 1987).
44    % Version 2.9 made \csname\endcsname's "relax" local (December 1987).
45    % Version 2.91 fixed \outer\def\a0{}\a\a bug (April 1988).
46    % Version 2.92 fixed \patterns, also file names with complex macros (May 1988).
47    % Version 2.93 fixed negative halving in allocator when mem_min<0 (June 1988).
48    % Version 2.94 kept open_log_file from calling fatal_error (November 1988).
49    % Version 2.95 solved that problem a better way (December 1988).
50    % Version 2.96 corrected bug in "Infinite shrinkage" recovery (January 1989).
51    % Version 2.97 corrected blunder in creating 2.95 (February 1989).
52    % Version 2.98 omitted save_for_after at outer level (March 1989).
53    % Version 2.99 caught $$\begingroup\halign..$$ (June 1989).
54    % Version 2.991 caught .5\ifdim.6... (June 1989).
55    % Version 2.992 introduced major changes for 8-bit extensions (September 1989).
56    % Version 2.993 fixed a save_stack synchronization bug et alia (December 1989).
57    % Version 3.0 fixed unusual displays; was more \output robust (March 1990).
58    % Version 3.1 fixed nullfont, disabled \write{\the\prevgraf} (September 1990).
59    % Version 3.14 fixed unprintable font names and corrected typos (March 1991).
60    % Version 3.141 more of same; reconstituted ligatures better (March 1992).
61    % Version 3.1415 preserved nonexplicit kerns, tidied up (February 1993).
62    % Version 3.14159 allowed fontmemsize to change; bulletproofing (March 1995).
63    % Version 3.141592 fixed \xleaders, glueset, weird alignments (December 2002).
64    % Version 3.1415926 was a general cleanup with minor fixes (February 2008).
65    % Succesive versions have been checked and if needed fixes have been applied.
66    \stoptyping
67
68    Although considerable effort has been expended to make the \LUATEX\ program correct and
69    reliable, no warranty is implied; the authors disclaim any obligation or liability for damages,
70    including but not limited to special, indirect, or consequential damages arising out of or in
71    connection with the use or performance of this software. This work has been a \quote {labor
72    of love| and the authors (Hartmut Henkel, Taco Hoekwater, Hans Hagen and Luigi Scarso) hope that
73    users enjoy it.
74
75    After a decade years of experimenting and reaching a more or less stable state, \LUATEX\ 1.0 was
76    released and a few years later end 2018 we were at version 1.1 which is a meant to be a stable
77    version. No more substantial additions will take place (that happens in \LUAMETATEX). As a
78    follow up we decided to experiment with a stripped down version, basically the \TEX\ core
79    without backend and with minimal font and file management. We'll see where that ends.
80
81    {\em You will find a lot of comments that originate in original \TEX. We kept them as a side
82    effect of the conversion from \WEB\ to \CWEB. Because there is not much webbing going on here
83    eventually the files became regular \CCODE\ files with still potentially typeset comments. As
84    we add our own comments, and also comments are there from \PDFTEX, \ALEPH\ and \ETEX, we get a
85    curious mix. The best comments are of course from Don Knuth. All bad comments are ours. All
86    errors are ours too!
87
88    Not all comments make sense, because some things are implemented differently, for instance some
89    memory management. But the principles of tokens and nodes stayed. It anyway means that you
90    sometimes need to keep in mind that the explanation is more geared to traditional \TEX. But that's
91    not a bad thing. Sorry Don for any confusion we introduced. The readers should have a copy of the
92    \TEX\ books at hand anyway.}
93
94    A large piece of software like \TEX\ has inherent complexity that cannot be reduced below a certain
95    level of difficulty, although each individual part is fairly simple by itself. The \WEB\ language
96    is intended to make the algorithms as readable as possible, by reflecting the way the individual
97    program pieces fit together and by providing the cross-references that connect different parts.
98    Detailed comments about what is going on, and about why things were done in certain ways, have been
99    liberally sprinkled throughout the program. These comments explain features of the implementation,
100    but they rarely attempt to explain the \TeX\ language itself, since the reader is supposed to be
101    familiar with {\em The \TeX book}.
102
103    The present implementation has a long ancestry, beginning in the summer of~1977, when Michael~F.
104    Plass and Frank~M. Liang designed and coded a prototype based on some specifications that the
105    author had made in May of that year. This original proto\TEX\ included macro definitions and
106    elementary manipulations on boxes and glue, but it did not have line-breaking, page-breaking,
107    mathematical formulas, alignment routines, error recovery, or the present semantic nest;
108    furthermore, it used character lists instead of token lists, so that a control sequence like |
109    \halign| was represented by a list of seven characters. A complete version of \TEX\ was designed
110    and coded by the author in late 1977 and early 1978; that program, like its prototype, was
111    written in the SAIL language, for which an excellent debugging system was available. Preliminary
112    plans to convert the SAIL code into a form somewhat like the present \quotation {web} were
113    developed by Luis Trabb~Pardo and the author at the beginning of 1979, and a complete
114    implementation was created by Ignacio~A. Zabala in 1979 and 1980. The \TEX82 program, which was
115    written by the author during the latter part of 1981 and the early part of 1982, also
116    incorporates ideas from the 1979 implementation of \TeX\ in {MESA} that was written by Leonidas
117    Guibas, Robert Sedgewick, and Douglas Wyatt at the Xerox Palo Alto Research Center. Several
118    hundred refinements were introduced into \TEX82 based on the experiences gained with the original
119    implementations, so that essentially every part of the system has been substantially improved.
120    After the appearance of Version 0 in September 1982, this program benefited greatly from the
121    comments of many other people, notably David~R. Fuchs and Howard~W. Trickey. A final revision in
122    September 1989 extended the input character set to eight-bit codes and introduced the ability to
123    hyphenate words from different languages, based on some ideas of Michael~J. Ferguson.
124
125    No doubt there still is plenty of room for improvement, but the author is firmly committed to
126    keeping \TEX82 frozen from now on; stability and reliability are to be its main virtues. On the
127    other hand, the \WEB\ description can be extended without changing the core of \TEX82 itself,
128    and the program has been designed so that such extensions are not extremely difficult to make.
129    The |banner| string defined here should be changed whenever \TEX\ undergoes any modifications,
130    so that it will be clear which version of \TEX\ might be the guilty party when a problem arises.
131
132    This program contains code for various features extending \TEX, therefore this program is called
133    \LUATEX\ and not \TEX; the official name \TEX\ by itself is reserved for software systems that
134    are fully compatible with each other. A special test suite called the \quote {TRIP test} is
135    available for helping to determine whether a particular implementation deserves to be known
136    as \TEX\ [cf.~Stanford Computer Science report CS1027, November 1984].
137
138    A similar test suite called the \quote {e-TRIP test} is available for helping to determine
139    whether a particular implementation deserves to be known as \ETEX.
140
141    {\em NB: Although \LUATEX\ can pass lots of the test it's not trip compatible: we use \UTF,
142    support different font models, have adapted the backend to todays demands, etc.}
143
144    This is the first of many sections of \TEX\ where global variables are defined.
145
146    The \LUAMETATEX\ source is an adaptation of the \LUATEX\ source and it took quite a bit of
147    work to get there. I tried to stay close to the original Knuthian names and code but there are
148    all kind of subtle differences with the \LUATEX\ code, which came from the \PASCAL\ code. And
149    yes, all errors are mine (Hans).
150
151*/
152
153/*tex
154
155    This program (we're talking of original \TEX\ here) has two important variations:
156
157    \startitemize[n]
158        \startitem
159            There is a long and slow version called \INITEX, which does the extra calculations
160            needed to initialize \TEX's internal tables; and
161        \stopitem
162        \startitem
163            there is a shorter and faster production version, which cuts the initialization to
164            a bare minimum.
165        \stopitem
166    \stopitemize
167
168    Remark: Due to faster processors and media, the difference is not as large as it used to be,
169    so \quote {long} and \quote {slow] no longer really apply. Making a \PDFTEX\ format takes 6
170    seconds because patterns are loaded in \UTF-8 format which demands interpretation, while
171    \XETEX\ which has native \UTF-8\ support takes just over 3 seconds. Making \CONTEXT\ \LMTX\
172    format with \LUAMETATEX taked 2.54 seconds, and it involves loading hundreds of files with
173    megabytes of code (much more than in \MKII). So it's not that bad. Loading a format file for
174    a production run takes less than half a second (which includes quite some \LUA\ initialization).
175    On a more modern machine these times are less of course.
176
177*/
178
179main_state_info lmt_main_state = {
180    .run_state     = production_state,
181    .ready_already = output_disabled_state,
182    .start_time    = 0.0,
183};
184
185/*tex
186
187    This state registers if are we are |INITEX| with |ini_version|, keeps the \TEX\ width of
188    context lines on terminal error messages in |error_line| and the width of first lines of
189    contexts in terminal error messages in |half_error_line| which should be between 30 and
190    |error_line - 15|. The width of longest text lines output, which should be at least 60,
191    is strored in |max_print_line| and the maximum number of strings, which must not exceed
192    |max_halfword| is kept in |max_strings|.
193
194    The number of strings available after format loaded is |strings_free|, the maximum number of
195    characters simultaneously present in current lines of open files and in control sequences
196    between |\csname| and |\endcsname|, which must not exceed |max_halfword|, is kept in
197    |buf_size|. The maximum number of simultaneous input sources is in |stack_size| and the
198    maximum number of input files and error insertions that can be going on simultaneously in
199    |max_in_open|. The maximum number of simultaneous macro parameters is in |param_size| and
200    the maximum number of semantic levels simultaneously active in |nest_size|. The space for
201    saving values outside of current group, which must be at most |max_halfword|, is in
202    |save_size| and the depth of recursive calls of the |expand| procedure is limited by
203    |expand_depth|.
204
205    The times recent outputs that didn't ship anything out is tracked with |dead_cycles|. All
206    these (formally single global) variables are collected in one state structure. (The error
207    reporting is to some extent an implementation detail. As errors can be intercepted by \LUA\
208    we keep things simple.)
209
210    We have noted that there are two versions of \TEX82. One, called \INITEX, has to be run
211    first; it initializes everything from scratch, without reading a format file, and it has the
212    capability of dumping a format file. The other one is called \VIRTEX; it is a \quote {virgin}
213    program that needs to input a format file in order to get started. (This model has been
214    adapted for a long time by the \TEX\ distributions, that ship multiple platforms and provide a
215    large infrastructure.)
216
217    For \LUATEX\ it is important to know that we still dump a format. But, in order to gain speed
218    and a smaller footprint, we gzip the format (level 3). We also store some information that
219    makes an abort possible in case of an incompatible engine version, which is important as
220    \LUATEX\ develops. It is possible to store \LUA\ code in the format but not the current
221    upvalues so you still need to initialize. Also, traditional fonts are stored, as are extended
222    fonts but any additional information needed for instance to deal with \OPENTYPE\ fonts is to
223    be handled by \LUA\ code and therefore not present in the format. (Actually, this version no
224    longer stores fonts at all.)
225
226*/
227
228static void final_cleanup(int code);
229
230void tex_main_body(void)
231{
232
233    tex_engine_set_limits_data("errorlinesize",     &lmt_error_state.line_limits);
234    tex_engine_set_limits_data("halferrorlinesize", &lmt_error_state.half_line_limits);
235    tex_engine_set_limits_data("expandsize",        &lmt_expand_state.limits);
236
237    tex_engine_set_memory_data("buffersize",        &lmt_fileio_state.io_buffer_data);
238    tex_engine_set_memory_data("filesize",          &lmt_input_state.in_stack_data);
239    tex_engine_set_memory_data("fontsize",          &lmt_font_state.font_data);
240    tex_engine_set_memory_data("hashsize",          &lmt_hash_state.hash_data);
241    tex_engine_set_memory_data("inputsize",         &lmt_input_state.input_stack_data);
242    tex_engine_set_memory_data("languagesize",      &lmt_language_state.language_data);
243    tex_engine_set_memory_data("marksize",          &lmt_mark_state.mark_data);
244    tex_engine_set_memory_data("insertsize",        &lmt_insert_state.insert_data);
245    tex_engine_set_memory_data("nestsize",          &lmt_nest_state.nest_data);
246    tex_engine_set_memory_data("nodesize",          &lmt_node_memory_state.nodes_data);
247    tex_engine_set_memory_data("parametersize",     &lmt_input_state.parameter_stack_data);
248    tex_engine_set_memory_data("poolsize",          &lmt_string_pool_state.string_body_data);
249    tex_engine_set_memory_data("savesize",          &lmt_save_state.save_stack_data);
250    tex_engine_set_memory_data("stringsize",        &lmt_string_pool_state.string_pool_data);
251    tex_engine_set_memory_data("tokensize",         &lmt_token_memory_state.tokens_data);
252    tex_engine_set_memory_data("mvlsize",           &lmt_mvl_state.mvl_data);
253
254    tex_initialize_fileio_state();
255    tex_initialize_nest_state();
256    tex_initialize_mvl_state();
257    tex_initialize_save_stack();
258    tex_initialize_input_state();
259
260    if (lmt_main_state.run_state == initializing_state) {
261        tex_initialize_string_mem();
262    }
263
264    if (lmt_main_state.run_state == initializing_state) {
265        tex_initialize_string_pool();
266    }
267
268    if (lmt_main_state.run_state == initializing_state) {
269        tex_initialize_token_mem();
270        tex_initialize_hash_mem();
271    }
272
273    tex_initialize_errors();
274    tex_initialize_nesting();
275    tex_initialize_pagestate();
276    tex_initialize_levels();
277    tex_initialize_primitives();
278    tex_initialize_marks();
279
280    if (lmt_main_state.run_state == initializing_state) {
281        tex_initialize_inserts();
282    }
283
284    if (lmt_main_state.run_state == initializing_state) {
285        tex_initialize_node_mem();
286    }
287
288    tex_initialize_destructors();
289
290    if (lmt_main_state.run_state == initializing_state) {
291        tex_initialize_nodes();
292        tex_initialize_tokens();
293        tex_initialize_expansion();
294        tex_initialize_alignments();
295        tex_initialize_buildpage();
296        tex_initialize_active();
297        tex_initialize_equivalents();
298        tex_initialize_math_codes();
299        tex_initialize_text_codes();
300        tex_initialize_cat_codes(0);
301        tex_initialize_xx_codes();
302    }
303
304    tex_initialize_dump_state();
305    tex_initialize_variables();
306    tex_initialize_commands();
307    tex_initialize_fonts();
308
309    if (lmt_main_state.run_state == initializing_state) {
310        tex_initialize_languages();
311        tex_initialize_units();
312    }
313
314    lmt_main_state.ready_already = output_enabled_state;
315
316    /*tex in case we quit during initialization */
317
318    lmt_error_state.history = fatal_error_stop;
319
320    /*tex
321        Get the first line of input and prepare to start When we begin the following code, \TEX's
322        tables may still contain garbage; the strings might not even be present. Thus we must
323        proceed cautiously to get bootstrapped in.
324
325        But when we finish this part of the program, \TEX\ is ready to call on the |main_control|
326        routine to do its work.
327
328        This copies the command line:
329    */
330
331    tex_initialize_inputstack();
332
333    if (lmt_main_state.run_state == initializing_state) {
334        /* We start out fresh. */
335    } else if (tex_load_fmt_file()) {
336
337        tex_initialize_expansion();
338        tex_initialize_alignments();
339
340        aux_get_date_and_time(&time_par, &day_par, &month_par, &year_par, &lmt_engine_state.utc_time);
341
342        while ((lmt_input_state.cur_input.loc < lmt_input_state.cur_input.limit) && (lmt_fileio_state.io_buffer[lmt_input_state.cur_input.loc] == ' ')) {
343            ++lmt_input_state.cur_input.loc;
344        }
345    } else {
346        tex_normal_exit();
347    }
348
349    if (end_line_char_inactive) {
350        --lmt_input_state.cur_input.limit;
351    } else {
352        lmt_fileio_state.io_buffer[lmt_input_state.cur_input.limit] = (unsigned char) end_line_char_par;
353    }
354
355    aux_get_date_and_time(&time_par, &day_par, &month_par, &year_par, &lmt_engine_state.utc_time);
356
357    tex_initialize_math();
358
359    tex_fixup_selector(lmt_fileio_state.log_opened); /* hm, the log is not yet opened anyway */
360
361    tex_engine_check_configuration();
362
363    tex_initialize_directions();
364
365    if (! fitness_classes_par) {
366        fitness_classes_par = tex_default_fitness_classes(); 
367    }
368    par_passes_par = null;
369    par_passes_exception_par = null;
370
371    {
372        char *ptr = tex_engine_input_filename();
373        char *fln = NULL;
374        tex_check_job_name(ptr);
375        tex_open_log_file();
376        tex_engine_get_config_string("firstline", &fln);
377        if (fln) {
378            tex_any_string_start(fln); /* experiment, see context lmtx */
379        }
380        if (ptr) {
381            tex_start_input(ptr, null);
382        } else if (! fln) {
383            tex_emergency_message("startup error", "no input found, quitting");
384            tex_emergency_exit();
385        }
386    }
387
388    /*tex 
389        We assume that |ignore_depth_criterion_par| is unchanged. If needed we can always do 
390        this: 
391    */
392
393 /* cur_list.prev_depth = ignore_depth_criterion_par; */
394
395    /*tex Ready to go, so come to life. */
396
397    lmt_error_state.history = spotless;
398
399 // {
400 //     int dump = tex_main_control();
401 //     if (dump && lmt_main_state.run_state != initializing_state) {
402 //         /*tex Maybe we need to issue a warning here. For now we just ignore it. */
403 //         dump = 0;
404 //     }
405 //     final_cleanup(dump);
406 // }
407    final_cleanup(tex_main_control());
408
409    tex_close_files_and_terminate(0);
410
411    tex_normal_exit();
412}
413
414/*tex
415
416    Here we do whatever is needed to complete \TEX's job gracefully on the local operating system.
417    The code here might come into play after a fatal error; it must therefore consist entirely of
418    \quote {safe} operations that cannot produce error messages. For example, it would be a mistake
419    to call |str_room| or |make_string| at this time, because a call on |overflow| might lead to an
420    infinite loop.
421
422    Actually there's one way to get error messages, via |prepare_mag|; but that can't cause infinite
423    recursion.
424
425    This program doesn't bother to close the input files that may still be open.
426
427    We can decide to remove the reporting code here as it can (and in \CONTEXT\ will) be done in a
428    callback anyway, so we never enter that branch.
429
430    The output statistics go directly to the log file instead of using |print| commands, because
431    there's no need for these strings to take up |string_pool| memory.
432
433    We now assume a callback being set, if wanted at all, but we keep this as a reference so that
434    we know what is of interest:
435
436    \starttyping
437    void close_files_and_terminate(int error)
438    {
439        int callback_id = lmt_callback_defined(stop_run_callback);
440        if (fileio_state.log_opened) {
441            if (callback_id == 0) {
442                fprintf(print_state.log_file,
443                    "\n\nHere is how much memory " My_Name " used:\n"
444                );
445                fprintf(print_state.log_file,
446                    " %d strings out of %d\n",
447                    string_pool_state.string_pool_data.ptr       - string_pool_state.reserved,
448                    string_pool_state.string_pool_data.allocated - string_pool_state.reserved + STRING_OFFSET
449                );
450                fprintf(print_state.log_file,
451                    " %d multiletter control sequences out of %d + %d extra\n",
452                    hash_state.hash_data.real,
453                    hash_size,
454                    hash_state.hash_data.allocated
455                );
456                fprintf(print_state.log_file,
457                    " %d words of node memory allocated out of %d",
458                    node_memory_state.nodes_data.allocated,
459                    node_memory_state.nodes_data.size
460                );
461                fprintf(print_state.log_file,
462                    " %d words of token memory allocated out of %d",
463                    token_memory_state.tokens_data.allocated,
464                    token_memory_state.tokens_data.size
465                );
466                fprintf(print_state.log_file,
467                    " %d font%s using %d bytes\n",
468                    get_font_max_id(),
469                    (get_font_max_id() == 1 ? "" : "s"),
470                    font_state.font_bytes
471                );
472                fprintf(print_state.log_file,
473                    " %d input stack positions out of %d\n",
474                    input_state.input_stack_data.top,
475                    input_state.input_stack_data.size
476                );
477                fprintf(print_state.log_file,
478                    " %d nest stack positions out of %d\n",
479                    nest_state.nest_data.top,
480                    nest_state.nest_data.size
481                );
482                fprintf(print_state.log_file,
483                    " %d parameter stack positions out of %d\n",
484                    input_state.param_stack_data.top,
485                    input_state.param_stack_data.size
486                );
487                fprintf(print_state.log_file,
488                    " %d buffer stack positions out of %d\n",
489                    fileio_state.io_buffer_data.top,
490                    fileio_state.io_buffer_data.size
491                );
492                fprintf(print_state.log_file,
493                    " %d save stack positions out of %d\n",
494                    save_state.save_stack_data.top,
495                    save_state.save_stack_data.size
496                );
497            }
498            print_state.selector = print_state.selector - 2;
499            if ((print_state.selector == term_only_selector_code) && (callback_id == 0)) {
500                print_str_nl("Transcript written on ");
501                print_file_name((unsigned char *) fileio_state.log_name);
502                print_char('.');
503                print_ln();
504            }
505            close_log_file();
506        }
507        callback_id = lmt_callback_defined(wrapup_run_callback);
508        if (callback_id > 0) {
509            lmt_run_callback(lua_state.lua_instance, callback_id, "b->", error);
510        }
511        free_text_codes();
512        free_math_codes();
513        free_languages();
514    }
515    \stoptyping
516*/
517
518void tex_close_files_and_terminate(int error)
519{
520    int callback_id = lmt_callback_defined(wrapup_run_callback);
521    if (lmt_fileio_state.log_opened) {
522        tex_close_log_file();
523    }
524    if (callback_id > 0) {
525        lmt_run_callback(lmt_lua_state.lua_instance, callback_id, "b->", error);
526    }
527}
528
529/*tex
530
531    We get to the |final_cleanup| routine when |\end| or |\dump| has been scanned and it's all
532    over now.
533
534*/
535
536static void final_cleanup(int dump)
537{
538    int badrun = 0;
539    if (! lmt_fileio_state.job_name) {
540        tex_open_log_file ();
541    }
542    tex_cleanup_directions();
543    while (lmt_input_state.input_stack_data.ptr > 0)
544        if (lmt_input_state.cur_input.state == token_list_state) {
545            tex_end_token_list();
546        } else {
547            tex_end_file_reading();
548        }
549    while (lmt_input_state.open_files > 0) {
550        tex_report_stop_file();
551        --lmt_input_state.open_files;
552    }
553    if (cur_level > level_one) {
554        tex_print_format("(\\end occurred inside a group at level %i)", cur_level - level_one);
555        tex_show_save_groups();
556        badrun = 1;
557    }
558    while (lmt_condition_state.cond_ptr) {
559        halfword t;
560        if (lmt_condition_state.if_line != 0) {
561            tex_print_format("(\\end occurred when %C on line %i was incomplete)", if_test_cmd, lmt_condition_state.cur_if, lmt_condition_state.if_line);
562            badrun = 2;
563        } else {
564            tex_print_format("(\\end occurred when %C was incomplete)");
565            badrun = 3;
566        }
567        lmt_condition_state.if_line = if_limit_line(lmt_condition_state.cond_ptr);
568        lmt_condition_state.cur_if = node_subtype(lmt_condition_state.cond_ptr);
569        t = lmt_condition_state.cond_ptr;
570        lmt_condition_state.cond_ptr = node_next(lmt_condition_state.cond_ptr);
571        tex_flush_node(t);
572    }
573    if (lmt_print_state.selector == terminal_and_logfile_selector_code && lmt_callback_defined(stop_run_callback) == 0) {
574        if ((lmt_error_state.history == warning_issued) || (lmt_error_state.history != spotless && lmt_error_state.interaction < error_stop_mode)) {
575            lmt_print_state.selector = terminal_selector_code;
576            tex_print_message("see the transcript file for additional information");
577            lmt_print_state.selector = terminal_and_logfile_selector_code;
578        }
579    }
580    if (dump) {
581        tex_cleanup_alignments();
582        tex_cleanup_expansion();
583        if (lmt_main_state.run_state == initializing_state) {
584            for (int i = 0; i <= lmt_mark_state.mark_data.ptr; i++) {
585                tex_wipe_mark(i);
586            }
587            tex_flush_node_list(lmt_packaging_state.page_discards_head);
588            tex_flush_node_list(lmt_packaging_state.split_discards_head);
589            if (lmt_page_builder_state.last_glue != max_halfword) {
590                tex_flush_node(lmt_page_builder_state.last_glue);
591                lmt_page_builder_state.last_glue = max_halfword;
592            }
593            for (int i = 0; i <= lmt_insert_state.insert_data.ptr; i++) {
594                tex_wipe_insert(i);
595            }
596# if 0
597            for (int i = 1; i < max_chain_size; i++) {
598                halfword p = lmt_node_memory_state.free_chain[i];
599                while (p) {
600                    printf("free : node %i : %i (%s), subtype %i, size %i\n", p, node_type(p), lmt_interface.node_data[node_type(p)].name, node_subtype(p), i);
601                    p = node_next(p);
602                }
603            }
604            for (int i = 1; i < lmt_node_memory_state.nodes_data.allocated; i++) {
605                halfword s = lmt_node_memory_state.nodesizes[i];
606                if (s) {
607                    printf("slot : node %i : %i (%s), subtype %i, size %i\n", i, node_type(i), lmt_interface.node_data[node_type(i)].name, node_subtype(i), s);
608                }
609            }
610# endif
611            tex_store_fmt_file();
612        } else {
613            tex_print_message("\\dump is performed only by INITEX");
614            badrun = 4;
615        }
616    }
617    if (lmt_callback_defined(stop_run_callback)) {
618        /*
619            We don't issue the error callback here (yet), mainly because we don't really know what
620            bad things happened. This might evolve as currently it is not seen as fatal error.
621        */
622        lmt_run_callback(lmt_lua_state.lua_instance, stop_run_callback, "d->", badrun);
623    }
624}
625
626