Coverage Report

Created: 2025-07-12 06:24

/src/jq/src/jv_print.c
Line
Count
Source (jump to first uncovered line)
1
#include <assert.h>
2
#include <stdio.h>
3
#include <float.h>
4
#include <string.h>
5
6
#ifdef WIN32
7
#include <windows.h>
8
#include <io.h>
9
#include <fileapi.h>
10
#endif
11
12
#include "jv.h"
13
#include "jv_dtoa.h"
14
#include "jv_dtoa_tsd.h"
15
#include "jv_unicode.h"
16
#include "jv_alloc.h"
17
#include "jv_private.h"
18
19
#ifndef MAX_PRINT_DEPTH
20
0
#define MAX_PRINT_DEPTH (256)
21
#endif
22
23
0
#define ESC "\033"
24
#define COL(c) (ESC "[" c "m")
25
0
#define COLRESET (ESC "[0m")
26
27
// Color table. See https://en.wikipedia.org/wiki/ANSI_escape_code#Colors
28
// for how to choose these. The order is same as jv_kind definition, and
29
// the last color is used for object keys.
30
#define DEFAULT_COLORS \
31
  {COL("0;90"),    COL("0;39"),      COL("0;39"),     COL("0;39"),\
32
   COL("0;32"),    COL("1;39"),      COL("1;39"),     COL("1;34")};
33
static const char *const default_colors[] = DEFAULT_COLORS;
34
static const char *colors[] = DEFAULT_COLORS;
35
0
#define COLORS_LEN (sizeof(colors) / sizeof(colors[0]))
36
0
#define FIELD_COLOR (colors[7])
37
38
static char *colors_buf = NULL;
39
0
int jq_set_colors(const char *code_str) {
40
0
  if (code_str == NULL)
41
0
    return 1;
42
43
  // the start of each color code in the env var, and the byte after the end of the last one
44
0
  const char *codes[COLORS_LEN + 1];
45
0
  size_t num_colors;
46
  // must be initialized before `goto default_colors`, used later to loop over every color
47
0
  size_t ci = 0;
48
49
0
  for (num_colors = 0;; num_colors++) {
50
0
    codes[num_colors] = code_str;
51
0
    code_str += strspn(code_str, "0123456789;");
52
0
    if (code_str[0] == '\0' || num_colors + 1 >= COLORS_LEN) {
53
0
      break;
54
0
    } else if (code_str[0] != ':') {
55
0
      return 0; // invalid character
56
0
    }
57
0
    code_str++;
58
0
  }
59
0
  if (codes[num_colors] != code_str) {
60
    // count the last color and store its end (plus one byte for consistency with starts)
61
    // an empty last color would be ignored (for cases like "" and "0:")
62
0
    num_colors++;
63
0
    codes[num_colors] = code_str + 1;
64
0
  } else if (num_colors == 0) {
65
0
    if (colors_buf != NULL) {
66
0
      jv_mem_free(colors_buf);
67
0
      colors_buf = NULL;
68
0
    }
69
0
    goto default_colors;
70
0
  }
71
72
0
  colors_buf = jv_mem_realloc(
73
0
    colors_buf,
74
    // add ESC '[' 'm' to each string
75
    // '\0' is already included in difference of codes
76
0
    codes[num_colors] - codes[0] + 3 * num_colors
77
0
  );
78
0
  char *cb = colors_buf;
79
0
  for (; ci < num_colors; ci++) {
80
0
    colors[ci] = cb;
81
0
    size_t len = codes[ci + 1] - 1 - codes[ci];
82
83
0
    cb[0] = ESC[0];
84
0
    cb[1] = '[';
85
0
    memcpy(cb + 2, codes[ci], len);
86
0
    cb[2 + len] = 'm';
87
0
    cb[3 + len] = '\0';
88
89
0
    cb += len + 4;
90
0
  }
91
0
  default_colors:
92
0
  for (; ci < COLORS_LEN; ci++)
93
0
    colors[ci] = default_colors[ci];
94
0
  return 1;
95
0
}
96
97
0
static void put_buf(const char *s, int len, FILE *fout, jv *strout, int is_tty) {
98
0
  if (strout) {
99
0
    *strout = jv_string_append_buf(*strout, s, len);
100
0
  } else {
101
#ifdef WIN32
102
  /* See util.h */
103
  if (is_tty) {
104
    wchar_t *ws;
105
    size_t wl;
106
    if (len == -1)
107
      len = strlen(s);
108
    wl = MultiByteToWideChar(CP_UTF8, 0, s, len, NULL, 0);
109
    ws = jv_mem_calloc(wl + 1, sizeof(*ws));
110
    if (!ws)
111
      return;
112
    wl = MultiByteToWideChar(CP_UTF8, 0, s, len, ws, wl + 1);
113
    ws[wl] = 0;
114
    WriteConsoleW((HANDLE)_get_osfhandle(fileno(fout)), ws, wl, NULL, NULL);
115
    free(ws);
116
  } else
117
    fwrite(s, 1, len, fout);
118
#else
119
0
  fwrite(s, 1, len, fout);
120
0
#endif
121
0
  }
122
0
}
123
124
0
static void put_char(char c, FILE* fout, jv* strout, int T) {
125
0
  put_buf(&c, 1, fout, strout, T);
126
0
}
127
128
0
static void put_str(const char* s, FILE* fout, jv* strout, int T) {
129
0
  put_buf(s, strlen(s), fout, strout, T);
130
0
}
131
132
0
static void put_indent(int n, int flags, FILE* fout, jv* strout, int T) {
133
0
  if (flags & JV_PRINT_TAB) {
134
0
    while (n--)
135
0
      put_char('\t', fout, strout, T);
136
0
  } else {
137
0
    n *= ((flags & (JV_PRINT_SPACE0 | JV_PRINT_SPACE1 | JV_PRINT_SPACE2)) >> 8);
138
0
    while (n--)
139
0
      put_char(' ', fout, strout, T);
140
0
  }
141
0
}
142
143
0
static void jvp_dump_string(jv str, int ascii_only, FILE* F, jv* S, int T) {
144
0
  assert(jv_get_kind(str) == JV_KIND_STRING);
145
0
  const char* i = jv_string_value(str);
146
0
  const char* end = i + jv_string_length_bytes(jv_copy(str));
147
0
  const char* cstart;
148
0
  int c = 0;
149
0
  char buf[32];
150
0
  put_char('"', F, S, T);
151
0
  while ((i = jvp_utf8_next((cstart = i), end, &c))) {
152
0
    assert(c != -1);
153
0
    int unicode_escape = 0;
154
0
    if (0x20 <= c && c <= 0x7E) {
155
      // printable ASCII
156
0
      if (c == '"' || c == '\\') {
157
0
        put_char('\\', F, S, T);
158
0
      }
159
0
      put_char(c, F, S, T);
160
0
    } else if (c < 0x20 || c == 0x7F) {
161
      // ASCII control character
162
0
      switch (c) {
163
0
      case '\b':
164
0
        put_char('\\', F, S, T);
165
0
        put_char('b', F, S, T);
166
0
        break;
167
0
      case '\t':
168
0
        put_char('\\', F, S, T);
169
0
        put_char('t', F, S, T);
170
0
        break;
171
0
      case '\r':
172
0
        put_char('\\', F, S, T);
173
0
        put_char('r', F, S, T);
174
0
        break;
175
0
      case '\n':
176
0
        put_char('\\', F, S, T);
177
0
        put_char('n', F, S, T);
178
0
        break;
179
0
      case '\f':
180
0
        put_char('\\', F, S, T);
181
0
        put_char('f', F, S, T);
182
0
        break;
183
0
      default:
184
0
        unicode_escape = 1;
185
0
        break;
186
0
      }
187
0
    } else {
188
0
      if (ascii_only) {
189
0
        unicode_escape = 1;
190
0
      } else {
191
0
        put_buf(cstart, i - cstart, F, S, T);
192
0
      }
193
0
    }
194
0
    if (unicode_escape) {
195
0
      if (c <= 0xffff) {
196
0
        snprintf(buf, sizeof(buf), "\\u%04x", c);
197
0
      } else {
198
0
        c -= 0x10000;
199
0
        snprintf(buf, sizeof(buf), "\\u%04x\\u%04x",
200
0
                0xD800 | ((c & 0xffc00) >> 10),
201
0
                0xDC00 | (c & 0x003ff));
202
0
      }
203
0
      put_str(buf, F, S, T);
204
0
    }
205
0
  }
206
0
  assert(c != -1);
207
0
  put_char('"', F, S, T);
208
0
}
209
210
0
static void put_refcnt(struct dtoa_context* C, int refcnt, FILE *F, jv* S, int T){
211
0
  char buf[JVP_DTOA_FMT_MAX_LEN];
212
0
  put_char(' ', F, S, T);
213
0
  put_char('(', F, S, T);
214
0
  put_str(jvp_dtoa_fmt(C, buf, refcnt), F, S, T);
215
0
  put_char(')', F, S, T);
216
0
}
217
218
0
static void jv_dump_term(struct dtoa_context* C, jv x, int flags, int indent, FILE* F, jv* S) {
219
0
  char buf[JVP_DTOA_FMT_MAX_LEN];
220
0
  const char* color = 0;
221
0
  double refcnt = (flags & JV_PRINT_REFCOUNT) ? jv_get_refcnt(x) - 1 : -1;
222
0
  if ((flags & JV_PRINT_COLOR) && jv_get_kind(x) != JV_KIND_INVALID) {
223
0
    color = colors[(int)jv_get_kind(x) - 1];
224
0
    put_str(color, F, S, flags & JV_PRINT_ISATTY);
225
0
  }
226
0
  if (indent > MAX_PRINT_DEPTH) {
227
0
    put_str("<skipped: too deep>", F, S, flags & JV_PRINT_ISATTY);
228
0
  } else switch (jv_get_kind(x)) {
229
0
  default:
230
0
  case JV_KIND_INVALID:
231
0
    if (flags & JV_PRINT_INVALID) {
232
0
      jv msg = jv_invalid_get_msg(jv_copy(x));
233
0
      if (jv_get_kind(msg) == JV_KIND_STRING) {
234
0
        put_str("<invalid:", F, S, flags & JV_PRINT_ISATTY);
235
0
        jvp_dump_string(msg, flags | JV_PRINT_ASCII, F, S, flags & JV_PRINT_ISATTY);
236
0
        put_char('>', F, S, flags & JV_PRINT_ISATTY);
237
0
      } else {
238
0
        put_str("<invalid>", F, S, flags & JV_PRINT_ISATTY);
239
0
      }
240
0
    } else {
241
0
      assert(0 && "Invalid value");
242
0
    }
243
0
    break;
244
0
  case JV_KIND_NULL:
245
0
    put_str("null", F, S, flags & JV_PRINT_ISATTY);
246
0
    break;
247
0
  case JV_KIND_FALSE:
248
0
    put_str("false", F, S, flags & JV_PRINT_ISATTY);
249
0
    break;
250
0
  case JV_KIND_TRUE:
251
0
    put_str("true", F, S, flags & JV_PRINT_ISATTY);
252
0
    break;
253
0
  case JV_KIND_NUMBER: {
254
0
    if (jvp_number_is_nan(x)) {
255
0
      jv_dump_term(C, jv_null(), flags, indent, F, S);
256
0
    } else {
257
0
#ifdef USE_DECNUM
258
0
      const char * literal_data = jv_number_get_literal(x);
259
0
      if (literal_data) {
260
0
        put_str(literal_data, F, S, flags & JV_PRINT_ISATTY);
261
0
      } else {
262
0
#endif
263
0
        double d = jv_number_value(x);
264
0
        if (d != d) {
265
          // JSON doesn't have NaN, so we'll render it as "null"
266
0
          put_str("null", F, S, flags & JV_PRINT_ISATTY);
267
0
        } else {
268
          // Normalise infinities to something we can print in valid JSON
269
0
          if (d > DBL_MAX) d = DBL_MAX;
270
0
          if (d < -DBL_MAX) d = -DBL_MAX;
271
0
          put_str(jvp_dtoa_fmt(C, buf, d), F, S, flags & JV_PRINT_ISATTY);
272
0
        }
273
0
      }
274
0
#ifdef USE_DECNUM
275
0
    }
276
0
#endif
277
0
    break;
278
0
  }
279
0
  case JV_KIND_STRING:
280
0
    jvp_dump_string(x, flags & JV_PRINT_ASCII, F, S, flags & JV_PRINT_ISATTY);
281
0
    if (flags & JV_PRINT_REFCOUNT)
282
0
      put_refcnt(C, refcnt, F, S, flags & JV_PRINT_ISATTY);
283
0
    break;
284
0
  case JV_KIND_ARRAY: {
285
0
    if (jv_array_length(jv_copy(x)) == 0) {
286
0
      put_str("[]", F, S, flags & JV_PRINT_ISATTY);
287
0
      break;
288
0
    }
289
0
    put_char('[', F, S, flags & JV_PRINT_ISATTY);
290
0
    jv_array_foreach(x, i, elem) {
291
0
      if (i!=0) {
292
0
        if (color) put_str(color, F, S, flags & JV_PRINT_ISATTY);
293
0
        put_char(',', F, S, flags & JV_PRINT_ISATTY);
294
0
      }
295
0
      if (color) put_str(COLRESET, F, S, flags & JV_PRINT_ISATTY);
296
0
      if (flags & JV_PRINT_PRETTY) {
297
0
        put_char('\n', F, S, flags & JV_PRINT_ISATTY);
298
0
        put_indent(indent + 1, flags, F, S, flags & JV_PRINT_ISATTY);
299
0
      }
300
0
      jv_dump_term(C, elem, flags, indent + 1, F, S);
301
0
    }
302
0
    if (flags & JV_PRINT_PRETTY) {
303
0
      put_char('\n', F, S, flags & JV_PRINT_ISATTY);
304
0
      put_indent(indent, flags, F, S, flags & JV_PRINT_ISATTY);
305
0
    }
306
0
    if (color) put_str(color, F, S, flags & JV_PRINT_ISATTY);
307
0
    put_char(']', F, S, flags & JV_PRINT_ISATTY);
308
0
    if (flags & JV_PRINT_REFCOUNT)
309
0
      put_refcnt(C, refcnt, F, S, flags & JV_PRINT_ISATTY);
310
0
    break;
311
0
  }
312
0
  case JV_KIND_OBJECT: {
313
0
    if (jv_object_length(jv_copy(x)) == 0) {
314
0
      put_str("{}", F, S, flags & JV_PRINT_ISATTY);
315
0
      break;
316
0
    }
317
0
    put_char('{', F, S, flags & JV_PRINT_ISATTY);
318
0
    int first = 1;
319
0
    int i = 0;
320
0
    jv keyset = jv_null();
321
0
    while (1) {
322
0
      jv key, value;
323
0
      if (flags & JV_PRINT_SORTED) {
324
0
        if (first) {
325
0
          keyset = jv_keys(jv_copy(x));
326
0
          i = 0;
327
0
        } else {
328
0
          i++;
329
0
        }
330
0
        if (i >= jv_array_length(jv_copy(keyset))) {
331
0
          jv_free(keyset);
332
0
          break;
333
0
        }
334
0
        key = jv_array_get(jv_copy(keyset), i);
335
0
        value = jv_object_get(jv_copy(x), jv_copy(key));
336
0
      } else {
337
0
        if (first) {
338
0
          i = jv_object_iter(x);
339
0
        } else {
340
0
          i = jv_object_iter_next(x, i);
341
0
        }
342
0
        if (!jv_object_iter_valid(x, i)) break;
343
0
        key = jv_object_iter_key(x, i);
344
0
        value = jv_object_iter_value(x, i);
345
0
      }
346
347
0
      if (!first) {
348
0
        if (color) put_str(color, F, S, flags & JV_PRINT_ISATTY);
349
0
        put_char(',', F, S, flags & JV_PRINT_ISATTY);
350
0
      }
351
0
      if (color) put_str(COLRESET, F, S, flags & JV_PRINT_ISATTY);
352
0
      if (flags & JV_PRINT_PRETTY) {
353
0
        put_char('\n', F, S, flags & JV_PRINT_ISATTY);
354
0
        put_indent(indent + 1, flags, F, S, flags & JV_PRINT_ISATTY);
355
0
      }
356
357
0
      first = 0;
358
0
      if (color) put_str(FIELD_COLOR, F, S, flags & JV_PRINT_ISATTY);
359
0
      jvp_dump_string(key, flags & JV_PRINT_ASCII, F, S, flags & JV_PRINT_ISATTY);
360
0
      jv_free(key);
361
0
      if (color) put_str(COLRESET, F, S, flags & JV_PRINT_ISATTY);
362
363
0
      if (color) put_str(color, F, S, flags & JV_PRINT_ISATTY);
364
0
      put_char(':', F, S, flags & JV_PRINT_ISATTY);
365
0
      if (color) put_str(COLRESET, F, S, flags & JV_PRINT_ISATTY);
366
0
      if (flags & JV_PRINT_PRETTY) {
367
0
        put_char(' ', F, S, flags & JV_PRINT_ISATTY);
368
0
      }
369
370
0
      jv_dump_term(C, value, flags, indent + 1, F, S);
371
0
    }
372
0
    if (flags & JV_PRINT_PRETTY) {
373
0
      put_char('\n', F, S, flags & JV_PRINT_ISATTY);
374
0
      put_indent(indent, flags, F, S, flags & JV_PRINT_ISATTY);
375
0
    }
376
0
    if (color) put_str(color, F, S, flags & JV_PRINT_ISATTY);
377
0
    put_char('}', F, S, flags & JV_PRINT_ISATTY);
378
0
    if (flags & JV_PRINT_REFCOUNT)
379
0
      put_refcnt(C, refcnt, F, S, flags & JV_PRINT_ISATTY);
380
0
  }
381
0
  }
382
0
  jv_free(x);
383
0
  if (color) {
384
0
    put_str(COLRESET, F, S, flags & JV_PRINT_ISATTY);
385
0
  }
386
0
}
387
388
0
void jv_dumpf(jv x, FILE *f, int flags) {
389
0
  jv_dump_term(tsd_dtoa_context_get(), x, flags, 0, f, 0);
390
0
}
391
392
0
void jv_dump(jv x, int flags) {
393
0
  jv_dumpf(x, stdout, flags);
394
0
}
395
396
/* This one is nice for use in debuggers */
397
0
void jv_show(jv x, int flags) {
398
0
  if (flags == -1)
399
0
    flags = JV_PRINT_PRETTY | JV_PRINT_COLOR | JV_PRINT_INDENT_FLAGS(2);
400
0
  jv_dumpf(jv_copy(x), stderr, flags | JV_PRINT_INVALID);
401
0
  fflush(stderr);
402
0
}
403
404
0
jv jv_dump_string(jv x, int flags) {
405
0
  jv s = jv_string("");
406
0
  jv_dump_term(tsd_dtoa_context_get(), x, flags, 0, 0, &s);
407
0
  return s;
408
0
}
409
410
0
char *jv_dump_string_trunc(jv x, char *outbuf, size_t bufsize) {
411
0
  x = jv_dump_string(x, 0);
412
0
  const char *str = jv_string_value(x);
413
0
  const size_t len = strlen(str);
414
0
  strncpy(outbuf, str, bufsize);
415
0
  if (len > bufsize - 1 && bufsize >= 4) {
416
    // Indicate truncation with '...' without breaking UTF-8.
417
0
    const char *s = jvp_utf8_backtrack(outbuf + bufsize - 4, outbuf, NULL);
418
0
    if (s) bufsize = s + 4 - outbuf;
419
0
    strcpy(outbuf + bufsize - 4, "...");
420
0
  } else {
421
0
    outbuf[bufsize - 1] = '\0';
422
0
  }
423
0
  jv_free(x);
424
0
  return outbuf;
425
0
}