kit

kit
git clone https://git.ryansepassi.com/git/kit.git
Log | Files | Refs | README

gram_test.h (2211B)


      1 /* gram_test.h — shared test scaffolding for the in-process gram API tests.
      2  *
      3  * The public gram compiler API allocates through KitContext.heap and reports
      4  * diagnostics through KitContext.diag (there is no bespoke allocator/diagnostic
      5  * out-param). This header provides a libc-backed KitHeap and a KitContext that
      6  * routes diagnostics to stderr, so a test can just say:
      7  *
      8  *     const KitContext *ctx = gram_test_ctx();
      9  *     KitGramCompiled *c = NULL;
     10  *     if (kit_gram_compile_text(ctx, KIT_SLICE_LIT(src),
     11  *                               KIT_SLICE_LIT("t.ebnf"), &opts, &c) != KIT_OK)
     12  *       ...failure (a diagnostic was already printed to stderr)...
     13  */
     14 #ifndef GRAM_TEST_H
     15 #define GRAM_TEST_H
     16 
     17 #include <kit/core.h>
     18 #include <stdarg.h>
     19 #include <stdio.h>
     20 #include <stdlib.h>
     21 
     22 static void *gram_test_halloc(KitHeap *h, size_t n, size_t align) {
     23   (void)h;
     24   (void)align;
     25   return malloc(n ? n : 1);
     26 }
     27 static void *gram_test_hrealloc(KitHeap *h, void *p, size_t old, size_t n,
     28                                 size_t align) {
     29   (void)h;
     30   (void)old;
     31   (void)align;
     32   if (!n) {
     33     free(p);
     34     return NULL;
     35   }
     36   return realloc(p, n);
     37 }
     38 static void gram_test_hfree(KitHeap *h, void *p, size_t n) {
     39   (void)h;
     40   (void)n;
     41   free(p);
     42 }
     43 static KitHeap gram_test_heap_v = {gram_test_halloc, gram_test_hrealloc,
     44                                    gram_test_hfree, NULL};
     45 
     46 static void gram_test_diag(KitDiagSink *s, KitDiagKind kind, KitSrcLoc loc,
     47                            const char *fmt, va_list ap) {
     48   (void)s;
     49   (void)kind;
     50   (void)loc;
     51   vfprintf(stderr, fmt, ap);
     52   fputc('\n', stderr);
     53 }
     54 static KitDiagSink gram_test_sink_v = {gram_test_diag, NULL, 0, 0};
     55 
     56 /* The libc-backed heap, for tests that need a KitHeap directly (e.g. to build an
     57  * in-memory KitWriter for kit_gram_dump_sexpr / kit_gram_emit_c). */
     58 static inline KitHeap *gram_test_heap(void) { return &gram_test_heap_v; }
     59 
     60 /* A KitContext over a libc heap, diagnostics to stderr. */
     61 static inline const KitContext *gram_test_ctx(void) {
     62   static KitContext ctx;
     63   ctx.heap = &gram_test_heap_v;
     64   ctx.file_io = NULL;
     65   ctx.diag = &gram_test_sink_v;
     66   ctx.profiler = NULL;
     67   ctx.now = -1;
     68   return &ctx;
     69 }
     70 
     71 #endif /* GRAM_TEST_H */