texmainbody.c /size: 28 Kb    last modification: 2024-01-16 10:22
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 havebeen 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
253    tex_initialize_fileio_state();
254    tex_initialize_nest_state();
255    tex_initialize_save_stack();
256    tex_initialize_input_state();
257
258    if (lmt_main_state.run_state == initializing_state) {
259        tex_initialize_string_mem();
260    }
261
262    if (lmt_main_state.run_state == initializing_state) {
263        tex_initialize_string_pool();
264    }
265
266    if (lmt_main_state.run_state == initializing_state) {
267        tex_initialize_token_mem();
268        tex_initialize_hash_mem();
269    }
270
271    tex_initialize_errors();
272    tex_initialize_nesting();
273    tex_initialize_pagestate();
274    tex_initialize_levels();
275    tex_initialize_primitives();
276    tex_initialize_marks();
277
278    if (lmt_main_state.run_state == initializing_state) {
279        tex_initialize_inserts();
280    }
281
282    if (lmt_main_state.run_state == initializing_state) {
283        tex_initialize_node_mem();
284    }
285
286    if (lmt_main_state.run_state == initializing_state) {
287        tex_initialize_nodes();
288        tex_initialize_tokens();
289        tex_initialize_expansion();
290        tex_initialize_alignments();
291        tex_initialize_buildpage();
292        tex_initialize_active();
293        tex_initialize_equivalents();
294        tex_initialize_math_codes();
295        tex_initialize_text_codes();
296        tex_initialize_cat_codes(0);
297        tex_initialize_xx_codes();
298    }
299
300    tex_initialize_dump_state();
301    tex_initialize_variables();
302    tex_initialize_commands();
303    tex_initialize_fonts();
304
305    if (lmt_main_state.run_state == initializing_state) {
306        tex_initialize_languages();
307        tex_initialize_units();
308    }
309
310    lmt_main_state.ready_already = output_enabled_state;
311
312    /*tex in case we quit during initialization */
313
314    lmt_error_state.history = fatal_error_stop;
315
316    /*tex
317        Get the first line of input and prepare to start When we begin the following code, \TEX's
318        tables may still contain garbage; the strings might not even be present. Thus we must
319        proceed cautiously to get bootstrapped in.
320
321        But when we finish this part of the program, \TEX\ is ready to call on the |main_control|
322        routine to do its work.
323
324        This copies the command line:
325    */
326
327    tex_initialize_inputstack();
328
329    if (lmt_main_state.run_state == initializing_state) {
330        /* We start out fresh. */
331    } else if (tex_load_fmt_file()) {
332
333        tex_initialize_expansion();
334        tex_initialize_alignments();
335
336        aux_get_date_and_time(&time_par, &day_par, &month_par, &year_par, &lmt_engine_state.utc_time);
337
338        while ((lmt_input_state.cur_input.loc < lmt_input_state.cur_input.limit) && (lmt_fileio_state.io_buffer[lmt_input_state.cur_input.loc] == ' ')) {
339            ++lmt_input_state.cur_input.loc;
340        }
341    } else {
342        tex_normal_exit();
343    }
344
345    if (end_line_char_inactive) {
346        --lmt_input_state.cur_input.limit;
347    } else {
348        lmt_fileio_state.io_buffer[lmt_input_state.cur_input.limit] = (unsigned char) end_line_char_par;
349    }
350
351    aux_get_date_and_time(&time_par, &day_par, &month_par, &year_par, &lmt_engine_state.utc_time);
352
353    tex_initialize_math();
354
355    tex_fixup_selector(lmt_fileio_state.log_opened); /* hm, the log is not yet opened anyway */
356
357    tex_engine_check_configuration();
358
359    tex_initialize_directions();
360
361    {
362        char *ptr = tex_engine_input_filename();
363        char *fln = NULL;
364        tex_check_job_name(ptr);
365        tex_open_log_file();
366        tex_engine_get_config_string("firstline", &fln);
367        if (fln) {
368            tex_any_string_start(fln); /* experiment, see context lmtx */
369        }
370        if (ptr) {
371            tex_start_input(ptr, null);
372        } else if (! fln) {
373            tex_emergency_message("startup error", "no input found, quitting");
374            tex_emergency_exit();
375        }
376    }
377
378    /*tex 
379        We assume that |ignore_depth_criterion_par| is unchanged. If needed we can always do 
380        this: 
381    */
382
383 /* cur_list.prev_depth = ignore_depth_criterion_par; */
384
385    /*tex Ready to go, so come to life. */
386
387    lmt_error_state.history = spotless;
388
389 // {
390 //     int dump = tex_main_control();
391 //     if (dump && lmt_main_state.run_state != initializing_state) {
392 //         /*tex Maybe we need to issue a warning here. For now we just ignore it. */
393 //         dump = 0;
394 //     }
395 //     final_cleanup(dump);
396 // }
397    final_cleanup(tex_main_control());
398
399    tex_close_files_and_terminate(0);
400
401    tex_normal_exit();
402}
403
404/*tex
405
406    Here we do whatever is needed to complete \TEX's job gracefully on the local operating system.
407    The code here might come into play after a fatal error; it must therefore consist entirely of
408    \quote {safe} operations that cannot produce error messages. For example, it would be a mistake
409    to call |str_room| or |make_string| at this time, because a call on |overflow| might lead to an
410    infinite loop.
411
412    Actually there's one way to get error messages, via |prepare_mag|; but that can't cause infinite
413    recursion.
414
415    This program doesn't bother to close the input files that may still be open.
416
417    We can decide to remove the reporting code here as it can (and in \CONTEXT\ will) be done in a
418    callback anyway, so we never enter that branch.
419
420    The output statistics go directly to the log file instead of using |print| commands, because
421    there's no need for these strings to take up |string_pool| memory.
422
423    We now assume a callback being set, if wanted at all, but we keep this as a reference so that
424    we know what is of interest:
425
426    \starttyping
427    void close_files_and_terminate(int error)
428    {
429        int callback_id = lmt_callback_defined(stop_run_callback);
430        if (fileio_state.log_opened) {
431            if (callback_id == 0) {
432                fprintf(print_state.log_file,
433                    "\n\nHere is how much memory " My_Name " used:\n"
434                );
435                fprintf(print_state.log_file,
436                    " %d strings out of %d\n",
437                    string_pool_state.string_pool_data.ptr       - string_pool_state.reserved,
438                    string_pool_state.string_pool_data.allocated - string_pool_state.reserved + STRING_OFFSET
439                );
440                fprintf(print_state.log_file,
441                    " %d multiletter control sequences out of %d + %d extra\n",
442                    hash_state.hash_data.real,
443                    hash_size,
444                    hash_state.hash_data.allocated
445                );
446                fprintf(print_state.log_file,
447                    " %d words of node memory allocated out of %d",
448                    node_memory_state.nodes_data.allocated,
449                    node_memory_state.nodes_data.size
450                );
451                fprintf(print_state.log_file,
452                    " %d words of token memory allocated out of %d",
453                    token_memory_state.tokens_data.allocated,
454                    token_memory_state.tokens_data.size
455                );
456                fprintf(print_state.log_file,
457                    " %d font%s using %d bytes\n",
458                    get_font_max_id(),
459                    (get_font_max_id() == 1 ? "" : "s"),
460                    font_state.font_bytes
461                );
462                fprintf(print_state.log_file,
463                    " %d input stack positions out of %d\n",
464                    input_state.input_stack_data.top,
465                    input_state.input_stack_data.size
466                );
467                fprintf(print_state.log_file,
468                    " %d nest stack positions out of %d\n",
469                    nest_state.nest_data.top,
470                    nest_state.nest_data.size
471                );
472                fprintf(print_state.log_file,
473                    " %d parameter stack positions out of %d\n",
474                    input_state.param_stack_data.top,
475                    input_state.param_stack_data.size
476                );
477                fprintf(print_state.log_file,
478                    " %d buffer stack positions out of %d\n",
479                    fileio_state.io_buffer_data.top,
480                    fileio_state.io_buffer_data.size
481                );
482                fprintf(print_state.log_file,
483                    " %d save stack positions out of %d\n",
484                    save_state.save_stack_data.top,
485                    save_state.save_stack_data.size
486                );
487            }
488            print_state.selector = print_state.selector - 2;
489            if ((print_state.selector == term_only_selector_code) && (callback_id == 0)) {
490                print_str_nl("Transcript written on ");
491                print_file_name((unsigned char *) fileio_state.log_name);
492                print_char('.');
493                print_ln();
494            }
495            close_log_file();
496        }
497        callback_id = lmt_callback_defined(wrapup_run_callback);
498        if (callback_id > 0) {
499            lmt_run_callback(lua_state.lua_instance, callback_id, "b->", error);
500        }
501        free_text_codes();
502        free_math_codes();
503        free_languages();
504    }
505    \stoptyping
506*/
507
508void tex_close_files_and_terminate(int error)
509{
510    int callback_id = lmt_callback_defined(wrapup_run_callback);
511    if (lmt_fileio_state.log_opened) {
512        tex_close_log_file();
513    }
514    if (callback_id > 0) {
515        lmt_run_callback(lmt_lua_state.lua_instance, callback_id, "b->", error);
516    }
517}
518
519/*tex
520
521    We get to the |final_cleanup| routine when |\end| or |\dump| has been scanned and it's all
522    over now.
523
524*/
525
526static void final_cleanup(int dump)
527{
528    int badrun = 0;
529    if (! lmt_fileio_state.job_name) {
530        tex_open_log_file ();
531    }
532    tex_cleanup_directions();
533    while (lmt_input_state.input_stack_data.ptr > 0)
534        if (lmt_input_state.cur_input.state == token_list_state) {
535            tex_end_token_list();
536        } else {
537            tex_end_file_reading();
538        }
539    while (lmt_input_state.open_files > 0) {
540        tex_report_stop_file();
541        --lmt_input_state.open_files;
542    }
543    if (cur_level > level_one) {
544        tex_print_format("(\\end occurred inside a group at level %i)", cur_level - level_one);
545        tex_show_save_groups();
546        badrun = 1;
547    }
548    while (lmt_condition_state.cond_ptr) {
549        halfword t;
550        if (lmt_condition_state.if_line != 0) {
551            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);
552            badrun = 2;
553        } else {
554            tex_print_format("(\\end occurred when %C was incomplete)");
555            badrun = 3;
556        }
557        lmt_condition_state.if_line = if_limit_line(lmt_condition_state.cond_ptr);
558        lmt_condition_state.cur_if = node_subtype(lmt_condition_state.cond_ptr);
559        t = lmt_condition_state.cond_ptr;
560        lmt_condition_state.cond_ptr = node_next(lmt_condition_state.cond_ptr);
561        tex_flush_node(t);
562    }
563    if (lmt_print_state.selector == terminal_and_logfile_selector_code && lmt_callback_defined(stop_run_callback) == 0) {
564        if ((lmt_error_state.history == warning_issued) || (lmt_error_state.history != spotless && lmt_error_state.interaction < error_stop_mode)) {
565            lmt_print_state.selector = terminal_selector_code;
566            tex_print_message("see the transcript file for additional information");
567            lmt_print_state.selector = terminal_and_logfile_selector_code;
568        }
569    }
570    if (dump) {
571        tex_cleanup_alignments();
572        tex_cleanup_expansion();
573        if (lmt_main_state.run_state == initializing_state) {
574            for (int i = 0; i <= lmt_mark_state.mark_data.ptr; i++) {
575                tex_wipe_mark(i);
576            }
577            tex_flush_node_list(lmt_packaging_state.page_discards_head);
578            tex_flush_node_list(lmt_packaging_state.split_discards_head);
579            if (lmt_page_builder_state.last_glue != max_halfword) {
580                tex_flush_node(lmt_page_builder_state.last_glue);
581            }
582            for (int i = 0; i <= lmt_insert_state.insert_data.ptr; i++) {
583                tex_wipe_insert(i);
584            }
585            tex_store_fmt_file();
586        } else {
587            tex_print_message("\\dump is performed only by INITEX");
588            badrun = 4;
589        }
590    }
591    if (lmt_callback_defined(stop_run_callback)) {
592        /*
593            We don't issue the error callback here (yet), mainly because we don't really know what
594            bad things happened. This might evolve as currently it is not seen as fatal error.
595        */
596        lmt_run_callback(lmt_lua_state.lua_instance, stop_run_callback, "d->", badrun);
597    }
598}
599
600