summaryrefslogtreecommitdiff
path: root/source/luametatex/source/lua/lmtcallbacklib.c
blob: 8724cdd6f3132fb4c2757c243a2773a6f89320e9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
/*
    See license.txt in the root of this project.
*/

# include "luametatex.h"

/*tex

    These are the supported callbacks (by name). This list must have the same size and order as the
    array in |luatexcallbackids.h|! We could have kept the names private here and maybe they will
    become that again. On the other hand we can now use them in reports.

*/

callback_state_info lmt_callback_state = {
    .metatable_id = 0,
    .padding      = 0,
    .values       = { 0 },
};

/* todo: use lua keywords instead */

static const char *callbacklib_names[total_callbacks] = {
    "", /*tex empty on purpose */
    "find_log_file",
    "find_format_file",
    "open_data_file",
    "process_jobname",
    "start_run",
    "stop_run",
    "define_font",
    "pre_output_filter",
    "buildpage_filter",
    "hpack_filter",
    "vpack_filter",
    "hyphenate",
    "ligaturing",
    "kerning",
    "glyph_run",
    "pre_linebreak_filter",
    "linebreak_filter",
    "post_linebreak_filter",
    "append_to_vlist_filter",
    "alignment_filter",
    "local_box_filter",
    "packed_vbox_filter",
    "mlist_to_hlist",
    "pre_dump",
    "start_file",
    "stop_file",
    "intercept_tex_error",
    "intercept_lua_error",
    "show_error_message",
    "show_warning_message",
    "hpack_quality",
    "vpack_quality",
    "insert_par",
    "append_line_filter",
    "build_page_insert",
 /* "fire_up_output", */
    "wrapup_run",
    "begin_paragraph",
    "paragraph_context",
 /* "get_math_char", */
    "math_rule",
    "make_extensible",
    "register_extensible",
    "show_whatsit",
    "get_attribute",
    "get_noad_class",
    "get_math_dictionary",
    "show_lua_call",
    "trace_memory",
    "handle_overload",
    "missing_character",
    "process_character",
};

/*tex

    This is the generic callback handler, inspired by the one described in the \LUA\ manual(s). It
    got adapted over time and can also handle some userdata arguments.

*/

static int callbacklib_aux_run(lua_State *L, int id, int special, const char *values, va_list vl, int top, int base)
{
    int narg = 0;
    int nres = 0;
    if (special == 2) {
        /*tex copy the enclosing table */
        lua_pushvalue(L, -2);
    }
    for (narg = 0; *values; narg++) {
        switch (*values++) {
            case callback_boolean_key:
                /*tex A boolean: */
                lua_pushboolean(L, va_arg(vl, int));
                break;
            case callback_charnum_key:
                /*tex A (8 bit) character: */
                {
                    char cs = (char) va_arg(vl, int);
                    lua_pushlstring(L, &cs, 1);
                }
                break;
            case callback_integer_key:
                /*tex An integer: */
                lua_pushinteger(L, va_arg(vl, int));
                break;
            case callback_line_key:
                /*tex A buffer section, with implied start: */
                lua_pushlstring(L, (char *) (lmt_fileio_state.io_buffer + lmt_fileio_state.io_first), (size_t) va_arg(vl, int));
                break;
            case callback_strnumber_key:
                /*tex A \TEX\ string (indicated by an index): */
                {
                    size_t len;
                    const char *s = tex_makeclstring(va_arg(vl, int), &len);
                    lua_pushlstring(L, s, len);
                }
                break;
            case callback_lstring_key:
                /*tex A \LUA\ string: */
                {
                    lstring *lstr = va_arg(vl, lstring *);
                    lua_pushlstring(L, (const char *) lstr->s, lstr->l);
                }
                break;
            case callback_node_key:
                /*tex A \TEX\ node: */
                lmt_push_node_fast(L, va_arg(vl, int));
                break;
            case callback_string_key:
                /*tex A \CCODE\ string: */
                lua_pushstring(L, va_arg(vl, char *));
                break;
            case '-':
                narg--;
                break;
            case '>':
                goto ENDARGS;
            default:
                ;
        }
    }
  ENDARGS:
    nres = (int) strlen(values);
    if (special == 1) {
        nres++;
    } else if (special == 2) {
        narg++;
    }
    {
        lmt_lua_state.saved_callback_count++;
        int i = lua_pcall(L, narg, nres, base);
        if (i) {
            /*tex
                We can't be more precise here as it could be called before \TEX\ initialization is
                complete.
            */
            lua_remove(L, top + 2);
            lmt_error(L, "run callback", id, (i == LUA_ERRRUN ? 0 : 1));
            lua_settop(L, top);
            return 0;
        }
    }
    if (nres == 0) {
        return 1;
    }
    nres = -nres;
    while (*values) {
        int t = lua_type(L, nres);
        switch (*values++) {
            case callback_boolean_key:
                switch (t) {
                    case LUA_TBOOLEAN:
                        *va_arg(vl, int *) = lua_toboolean(L, nres);
                        break;
                    case LUA_TNIL:
                        *va_arg(vl, int *) = 0;
                        break;
                    default:
                        return tex_formatted_error("callback", "boolean or nil expected, false or nil, not: %s\n", lua_typename(L, t));
                }
                break;
            /*
            case callback_charnum_key:
                break;
            */
            case callback_integer_key:
                switch (t) {
                    case LUA_TNUMBER:
                        *va_arg(vl, int *) = lmt_tointeger(L, nres);
                        break;
                    default:
                        return tex_formatted_error("callback", "number expected, not: %s\n", lua_typename(L, t));
                }
                break;
            case callback_line_key:
                switch (t) {
                    case LUA_TSTRING:
                        {
                            size_t len;
                            const char *s = lua_tolstring(L, nres, &len);
                            if (s && (len > 0)) {
                                int *bufloc = va_arg(vl, int *);
                                int ret = *bufloc;
                                if (tex_room_in_buffer(ret + (int) len)) {
                                    strncpy((char *) (lmt_fileio_state.io_buffer + ret), s, len);
                                    *bufloc += (int) len;
                                    /* while (len--) {  fileio_state.io_buffer[(*bufloc)++] = *s++; } */
                                    while ((*bufloc) - 1 > ret && lmt_fileio_state.io_buffer[(*bufloc) - 1] == ' ') {
                                        (*bufloc)--;
                                    }
                               } else {
                                    return 0;
                               }
                            }
                            /*tex We can assume no more arguments! */
                        }
                        break;
                    case LUA_TNIL:
                        /*tex We assume no more arguments! */
                        return 0;
                    default:
                        return tex_formatted_error("callback", "string or nil expected, not: %s\n", lua_typename(L, t));
                }
                break;
            case callback_strnumber_key:
                switch (t) {
                    case LUA_TSTRING:
                        {
                            size_t len;
                            const char *s = lua_tolstring(L, nres, &len);
                            if (s) {
                                *va_arg(vl, int *) = tex_maketexlstring(s, len);
                            } else {
                                /*tex |len| can be zero */
                                *va_arg(vl, int *) = 0;
                            }
                        }
                        break;
                    default:
                        return tex_formatted_error("callback", "string expected, not: %s\n", lua_typename(L, t));
               }
                break;
            case callback_lstring_key:
                switch (t) {
                    case LUA_TSTRING:
                        {
                            size_t len;
                            const char *s = lua_tolstring(L, nres, &len);
                            if (s && len > 0) {
                                lstring *lsret = lmt_memory_malloc(sizeof(lstring));
                                if (lsret) {
                                    lsret->s = lmt_memory_malloc((unsigned) (len + 1));
                                    if (lsret->s) {
                                        (void) memcpy(lsret->s, s, (len + 1));
                                        lsret->l = len;
                                        *va_arg(vl, lstring **) = lsret;
                                    } else {
                                        *va_arg(vl, int *) = 0;
                                    }
                                } else {
                                    *va_arg(vl, int *) = 0;
                                }
                            } else {
                                /*tex |len| can be zero */
                                *va_arg(vl, int *) = 0;
                            }
                        }
                        break;
                    default:
                        return tex_formatted_error("callback", "string expected, not: %s\n", lua_typename(L, t));
                }
                break;
            case callback_node_key:
                switch (t) {
                    case LUA_TUSERDATA:
                        *va_arg(vl, int *) = lmt_check_isnode(L, nres);
                        break;
                    default:
                        *va_arg(vl, int *) = null;
                        break;
                }
                break;
            case callback_string_key:
                switch (t) {
                    case LUA_TSTRING:
                        {
                            size_t len;
                            const char *s = lua_tolstring(L, nres, &len);
                            if (s) {
                                char *ss = lmt_memory_malloc((unsigned) (len + 1));
                                if (ss) {
                                    memcpy(ss, s, (len + 1));
                                 }
                                *va_arg(vl, char **) = ss;
                            } else {
                                *va_arg(vl, char **) = NULL;
                             // *va_arg(vl, int *) = 0;
                            }
                        }
                        break;
                    default:
                        return tex_formatted_error("callback", "string expected, not: %s\n", lua_typename(L, t));
                }
                break;
            case callback_result_key:
                switch (t) {
                    case LUA_TNIL:
                        *va_arg(vl, int *) = 0;
                        break;
                    case LUA_TBOOLEAN:
                        if (lua_toboolean(L, nres) == 0) {
                            *va_arg(vl, int *) = 0;
                            break;
                        } else {
                            return tex_formatted_error("callback", "string, false or nil expected, not: %s\n", lua_typename(L, t));
                        }
                    case LUA_TSTRING:
                        {
                            size_t len;
                            const char *s = lua_tolstring(L, nres, &len);
                            if (s) {
                                char *ss = lmt_memory_malloc((unsigned) (len + 1));
                                if (ss) {
                                    memcpy(ss, s, (len + 1));
                                    *va_arg(vl, char **) = ss;
                                } else {
                                   *va_arg(vl, char **) = NULL;
                                // *va_arg(vl, int *) = 0;
                                }
                            } else {
                                *va_arg(vl, char **) = NULL;
                             // *va_arg(vl, int *) = 0;
                            }
                        }
                        break;
                    default:
                        return tex_formatted_error("callback", "string, false or nil expected, not: %s\n", lua_typename(L, t));
                }
                break;
            default:
                return tex_formatted_error("callback", "invalid value type returned\n");
        }
        nres++;
    }
    return 1;
}

/*tex
    Especially the \IO\ related callbacks are registered once, for instance when a file is opened,
    and (re)used later. These are dealt with here.
*/

int lmt_run_saved_callback_close(lua_State *L, int r)
{
    int ret = 0;
    int stacktop = lua_gettop(L);
    lua_rawgeti(L, LUA_REGISTRYINDEX, r);
    lua_push_key(close);
    if (lua_rawget(L, -2) == LUA_TFUNCTION) {
        ret = lua_pcall(L, 0, 0, 0);
        if (ret) {
            return tex_formatted_error("lua", "error in close file callback") - 1;
        }
    }
    lua_settop(L, stacktop);
    return ret;
}

int lmt_run_saved_callback_line(lua_State *L, int r, int firstpos)
{
    int ret = -1; /* -1 is error, >= 0 is buffer length */
    int stacktop = lua_gettop(L);
    lua_rawgeti(L, LUA_REGISTRYINDEX, r);
    lua_push_key(reader);
    if (lua_rawget(L, -2) == LUA_TFUNCTION) {
        lua_pushvalue(L, -2);
        lmt_lua_state.file_callback_count++;
        ret = lua_pcall(L, 1, 1, 0);
        if (ret) {
            ret = tex_formatted_error("lua", "error in read line callback") - 1;
        } else if (lua_type(L, -1) == LUA_TSTRING) {
            size_t len;
            const char *s = lua_tolstring(L, -1, &len);
            if (s && len > 0) {
                while (len >= 1 && s[len-1] == ' ') {
                    len--;
                }
                if (len > 0) {
                    if (tex_room_in_buffer(firstpos + (int) len)) {
                        strncpy((char *) (lmt_fileio_state.io_buffer + firstpos), s, len);
                        ret = firstpos + (int) len;
                    } else {
                        tex_overflow_error("buffer", (int) len);
                        ret = 0;
                    }
                } else {
                    ret = 0;
                }
            } else {
                ret = 0;
            }
        } else {
            ret = -1;
        }
    }
    lua_settop(L, stacktop);
    return ret;
}

/*tex

    Many callbacks have a specific handler, so they don't use the previously mentioned generic one.
    The next bunch of helpers checks for them being set and deals invoking them as well as reporting
    errors.

*/

int lmt_callback_okay(lua_State *L, int i, int *top)
{
    *top = lua_gettop(L);
    lua_rawgeti(L, LUA_REGISTRYINDEX, lmt_callback_state.metatable_id);
    lua_pushcfunction(L, lmt_traceback); /* goes before function */
    if (lua_rawgeti(L, -2, i) == LUA_TFUNCTION) {
        lmt_lua_state.saved_callback_count++;
        return 1;
    } else {
        lua_pop(L, 3);
        return 0;
    }
}

void lmt_callback_error(lua_State *L, int top, int i)
{
    lua_remove(L, top + 2);
    lmt_error(L, "callback error", -1, (i == LUA_ERRRUN ? 0 : 1));
    lua_settop(L, top);
}

int lmt_run_and_save_callback(lua_State *L, int i, const char *values, ...)
{
    int top = 0;
    int ret = 0;
    if (lmt_callback_okay(L, i, &top)) {
        va_list args;
        va_start(args, values);
        ret = callbacklib_aux_run(L, i, 1, values, args, top, top + 2);
        va_end(args);
        if (ret > 0) {
            ret = lua_type(L, -1) == LUA_TTABLE ? luaL_ref(L, LUA_REGISTRYINDEX) : 0;
        }
        lua_settop(L, top);
    }
    return ret;
}

int lmt_run_callback(lua_State *L, int i, const char *values, ...)
{
    int top = 0;
    int ret = 0;
    if (lmt_callback_okay(L, i, &top)) {
        va_list args;
        va_start(args, values);
        ret = callbacklib_aux_run(L, i, 0, values, args, top, top + 2);
        va_end(args);
        lua_settop(L, top);
    }
    return ret;
}

void lmt_destroy_saved_callback(lua_State *L, int i)
{
    luaL_unref(L, LUA_REGISTRYINDEX, i);
}

static int callbacklib_callback_found(const char *s)
{
    if (s) {
        for (int cb = 0; cb < total_callbacks; cb++) {
            if (strcmp(callbacklib_names[cb], s) == 0) {
                return cb;
            }
        }
    }
    return -1;
}

static int callbacklib_callback_register(lua_State *L)
{
    const char *s = lua_tostring(L, 1);
    int cb = callbacklib_callback_found(s);
    if (cb >= 0) {
        switch (lua_type(L, 2)) {
            case LUA_TFUNCTION:
                lmt_callback_state.values[cb] = cb;
                break;
            case LUA_TBOOLEAN:
                if (lua_toboolean(L, 2)) {
                    goto BAD; /*tex Only |false| is valid. */
                }
                // fall through
            case LUA_TNIL:
                lmt_callback_state.values[cb] = -1;
                break;
        }
        lua_rawgeti(L, LUA_REGISTRYINDEX, lmt_callback_state.metatable_id);
        lua_pushvalue(L, 2); /*tex the function or nil */
        lua_rawseti(L, -2, cb);
        lua_rawseti(L, LUA_REGISTRYINDEX, lmt_callback_state.metatable_id);
        lua_pushinteger(L, cb);
        return 1;
    }
  BAD:
    lua_pushnil(L);
    return 1;
}

void lmt_run_memory_callback(const char* what, int success)
{
    lmt_run_callback(lmt_lua_state.lua_instance, trace_memory_callback, "Sb->", what, success);
    fflush(stdout);
}

/*tex

    The \LUA\ library that deals with callbacks has some diagnostic helpers that makes it possible
    to implement a higher level interface.

*/

static int callbacklib_callback_find(lua_State *L)
{
    const char *s = lua_tostring(L, 1);
    if (s) {
        int cb = callbacklib_callback_found(s);
        if (cb >= 0) {
            lua_rawgeti(L, LUA_REGISTRYINDEX, lmt_callback_state.metatable_id);
            lua_rawgeti(L, -1, cb);
            return 1;
        }
    }
    lua_pushnil(L);
    return 1;
}

static int callbacklib_callback_known(lua_State *L)
{
    const char *s = lua_tostring(L, 1);
    lua_pushboolean(L, s && (callbacklib_callback_found(s) >= 0));
    return 1;
}

static int callbacklib_callback_list(lua_State *L)
{
    lua_createtable(L, 0, total_callbacks);
    for (int cb = 1; cb < total_callbacks; cb++) {
        lua_pushstring(L, callbacklib_names[cb]);
        lua_pushboolean(L, lmt_callback_defined(cb));
        lua_rawset(L, -3);
    }
    return 1;
}

/* todo: language function calls */

void lmt_push_callback_usage(lua_State *L)
{
    lua_createtable(L, 0, 9);
    lua_push_integer_at_key(L, saved,    lmt_lua_state.saved_callback_count);
    lua_push_integer_at_key(L, file,     lmt_lua_state.file_callback_count);
    lua_push_integer_at_key(L, direct,   lmt_lua_state.direct_callback_count);
    lua_push_integer_at_key(L, function, lmt_lua_state.function_callback_count);
    lua_push_integer_at_key(L, value,    lmt_lua_state.value_callback_count);
    lua_push_integer_at_key(L, local,    lmt_lua_state.local_callback_count);
    lua_push_integer_at_key(L, bytecode, lmt_lua_state.bytecode_callback_count);
    lua_push_integer_at_key(L, message,  lmt_lua_state.message_callback_count);
    lua_push_integer_at_key(L, count,
        lmt_lua_state.saved_callback_count
      + lmt_lua_state.file_callback_count
      + lmt_lua_state.direct_callback_count
      + lmt_lua_state.function_callback_count
      + lmt_lua_state.value_callback_count
      + lmt_lua_state.local_callback_count
      + lmt_lua_state.bytecode_callback_count
      + lmt_lua_state.message_callback_count
    );
}

static int callbacklib_callback_usage(lua_State *L)
{
    lmt_push_callback_usage(L);
    return 1;
}

static const struct luaL_Reg callbacklib_function_list[] = {
    { "find",     callbacklib_callback_find     },
    { "known",    callbacklib_callback_known    },
    { "register", callbacklib_callback_register },
    { "list",     callbacklib_callback_list     },
    { "usage",    callbacklib_callback_usage    },
    { NULL,       NULL                          },
};

int luaopen_callback(lua_State *L)
{
    lua_newtable(L);
    luaL_setfuncs(L, callbacklib_function_list, 0);
    lua_newtable(L);
    lmt_callback_state.metatable_id = luaL_ref(L, LUA_REGISTRYINDEX);
    return 1;
}