// src/utils.h #ifndef INCLUDED_UTILS_H #define INCLUDED_UTILS_H #include #include #include #include #include #include "sv.h" #include "arena.h" #define NOP() do {} while (0) #define ARRAY_LENGTH(ARR) (sizeof (ARR)/sizeof (*(ARR))) #ifndef NDEBUG #include #define ASSERT assert #else #define ASSERT(...) NOP () #endif #define MALLOC malloc #define REALLOC realloc #define FREE free #define UNUSED(EXP) ((void) EXP) #define FALLTHROUGH __attribute__ ((__fallthrough__)) #define STRINGIFY(ARG) #ARG #define TO_STRING(ARG) STRINGIFY (ARG) #ifndef NDEBUG #define DEBUG(FMT, ...) \ fprintf (stderr, __FILE__ ":" TO_STRING (__LINE__) ": %s: " FMT "\n", \ __func__, ##__VA_ARGS__) #define LOG(FMT, ...) \ fprintf (stderr, __FILE__ ":" TO_STRING (__LINE__) ": %s: " FMT "\n", \ __func__, ##__VA_ARGS__) #else #define DEBUG(...) NOP () #define LOG(FMT, ...) \ fprintf (stderr, "%s: " FMT "\n", progname, ##__VA_ARGS__) #endif #define FATAL(FMT, ...) LOG ("fatal: " FMT, ##__VA_ARGS__) #define ERROR(FMT, ...) LOG ("error: " FMT, ##__VA_ARGS__) #define WARNING(FMT, ...) LOG ("warning: " FMT, ##__VA_ARGS__) #define NOTICE(FMT, ...) LOG ("notice: " FMT, ##__VA_ARGS__) #define INFO(FMT, ...) LOG ("info: " FMT, ##__VA_ARGS__) #define DIE(FMT, ...) do { \ FATAL (FMT, ##__VA_ARGS__); \ exit (EXIT_FAILURE); \ } while (0) #ifndef NDEBUG #define ASSERT_MSG(EXP, FMT, ...) do if (!(EXP)) { \ DEBUG (FMT, ##__VA_ARGS__); \ exit (EXIT_FAILURE); \ } while (0) #else #define ASSERT_MSG(EXP, FMT, ...) NOP () #endif #define MEASURE(FMT, ...) \ for (struct timespec _ts0, _ts1, *_once = NULL; \ clock_gettime (CLOCK_MONOTONIC, &_ts0), !_once; \ clock_gettime (CLOCK_MONOTONIC, &_ts1), \ DEBUG (FMT " %.6fs\n", ##__VA_ARGS__, \ (_ts1.tv_sec - _ts0.tv_sec ) + \ (_ts1.tv_nsec - _ts0.tv_nsec) / 1e9), \ _once += 1) #define MIN(A, B) ((A) <= (B) ? (A) : (B)) struct timer_scope { char *fmt; struct timespec start; }; static void timer_end (struct timer_scope *t) { struct timespec end; clock_gettime (CLOCK_MONOTONIC, &end); double s = ((end.tv_sec - t->start.tv_sec) + (end.tv_nsec - t->start.tv_nsec)/1e9); fprintf (stderr, t->fmt, s); if (t->fmt[strlen (t->fmt) - 1] != ' ') putc (' ', stderr); fprintf (stderr, "took %.6fs\n", s); free (t->fmt); } #define MEASURE_SCOPE(FMT, ...) \ __attribute__ ((cleanup (timer_end))) struct timer_scope __ts; \ asprintf (&__ts.fmt, \ __FILE__ ":" TO_STRING (__LINE__) ": %s: " FMT, \ __func__, ##__VA_ARGS__); \ clock_gettime (CLOCK_MONOTONIC, &__ts.start) struct location { struct { int line; int column; } beg; struct { int line; int column; } end; }; extern const char *progname; struct sv mmap_whole (int fd); struct sv read_until_eof (struct arena *, int fd); struct location find_location (struct sv haystack, struct sv needle); void print_location (const char *filename, struct location, int alignment, const char *format, ...); void print_back_trace (int skip); #endif // INCLUDED_UTILS_H // src/utils.h ends here