cpp

Coverage Report

Created: 2025-05-01 20:35

/home/uke/oil/mycpp/gc_builtins.cc
Line
Count
Source (jump to first uncovered line)
1
#include <errno.h>  // errno
2
#include <float.h>  // DBL_MIN, DBL_MAX
3
#include <math.h>   // INFINITY
4
#include <stdio.h>  // required for readline/readline.h (man readline)
5
6
#include "_build/detected-cpp-config.h"
7
#include "mycpp/runtime.h"
8
#ifdef HAVE_READLINE
9
  #include "cpp/frontend_pyreadline.h"
10
#endif
11
12
// Translation of Python's print().
13
5
void print(BigStr* s) {
14
5
  fputs(s->data_, stdout);  // print until first NUL
15
5
  fputc('\n', stdout);
16
5
}
17
18
0
BigStr* str(int i) {
19
0
  BigStr* s = OverAllocatedStr(kIntBufSize);
20
0
  int length = snprintf(s->data(), kIntBufSize, "%d", i);
21
0
  s->MaybeShrink(length);
22
0
  return s;
23
0
}
24
25
0
BigStr* str(double d) {
26
0
  char buf[64];  // overestimate, but we use snprintf() to be safe
27
28
0
  int n = sizeof(buf) - 2;  // in case we add '.0'
29
30
  // The round tripping test in mycpp/float_test.cc tells us:
31
  // %.9g - FLOAT round trip
32
  // %.17g - DOUBLE round trip
33
  // But this causes problems in practice, e.g. for 3.14, or 1/3
34
  // int length = snprintf(buf, n, "%.17g", d);
35
36
  // So use 1 less digit, which happens to match Python 3 and node.js (but not
37
  // Python 2)
38
0
  int length = snprintf(buf, n, "%.16g", d);
39
40
  // TODO: This may depend on LC_NUMERIC locale!
41
42
  // We may return the strings:
43
  //    inf  -inf   nan
44
  // But this shouldn't come up much, because Python code changes it to:
45
  //    INFINITY   -INFINITY   NAN
46
0
  if (strchr(buf, 'i') || strchr(buf, 'n')) {
47
0
    return StrFromC(buf);  // don't add .0
48
0
  }
49
50
  // Problem:
51
  // %f prints 3.0000000 and 3.500000
52
  // %g prints 3 and 3.5
53
  //
54
  // We want 3.0 and 3.5, so add '.0' in some cases
55
0
  if (!strchr(buf, '.')) {  // 12345 -> 12345.0
56
0
    buf[length] = '.';
57
0
    buf[length + 1] = '0';
58
0
    buf[length + 2] = '\0';
59
0
  }
60
61
0
  return StrFromC(buf);
62
0
}
63
// %a is a hexfloat form, probably don't need that
64
// int length = snprintf(buf, n, "%a", d);
65
66
// Do we need this API?  Or is mylib.InternedStr(BigStr* s, int start, int end)
67
// better for getting values out of Token.line without allocating?
68
//
69
// e.g. mylib.InternedStr(tok.line, tok.start, tok.start+1)
70
//
71
// Also for SmallStr, we don't care about interning.  Only for HeapStr.
72
73
0
BigStr* intern(BigStr* s) {
74
  // TODO: put in table gHeap.interned_
75
0
  return s;
76
0
}
77
78
// Print quoted string.  Called by StrFormat('%r').
79
// TODO: consider using J8 notation instead, since error messages show that
80
// string.
81
1
BigStr* repr(BigStr* s) {
82
  // Worst case: \0 becomes 4 bytes as '\\x00', and then two quote bytes.
83
1
  int n = len(s);
84
1
  int upper_bound = n * 4 + 2;
85
86
1
  BigStr* result = OverAllocatedStr(upper_bound);
87
88
  // Single quote by default.
89
1
  char quote = '\'';
90
1
  if (memchr(s->data_, '\'', n) && !memchr(s->data_, '"', n)) {
91
0
    quote = '"';
92
0
  }
93
1
  char* p = result->data_;
94
95
  // From PyString_Repr()
96
1
  *p++ = quote;
97
8
  for (int i = 0; i < n; ++i) {
98
7
    unsigned char c = static_cast<unsigned char>(s->data_[i]);
99
7
    if (c == quote || c == '\\') {
100
0
      *p++ = '\\';
101
0
      *p++ = c;
102
7
    } else if (c == '\t') {
103
0
      *p++ = '\\';
104
0
      *p++ = 't';
105
7
    } else if (c == '\n') {
106
0
      *p++ = '\\';
107
0
      *p++ = 'n';
108
7
    } else if (c == '\r') {
109
0
      *p++ = '\\';
110
0
      *p++ = 'r';
111
7
    } else if (0x20 <= c && c < 0x80) {
112
7
      *p++ = c;
113
7
    } else {
114
      // Unprintable becomes \xff.
115
      // TODO: Consider \yff.  This is similar to J8 strings, but we don't
116
      // decode UTF-8.
117
0
      sprintf(p, "\\x%02x", c & 0xff);
118
0
      p += 4;
119
0
    }
120
7
  }
121
1
  *p++ = quote;
122
1
  *p = '\0';
123
124
1
  int length = p - result->data_;
125
1
  result->MaybeShrink(length);
126
1
  return result;
127
1
}
128
129
// Helper functions that don't use exceptions.
130
131
2
bool StringToInt(const char* s, int length, int base, int* result) {
132
2
  if (length == 0) {
133
0
    return false;  // empty string isn't a valid integer
134
0
  }
135
136
  // Note: sizeof(int) is often 4 bytes on both 32-bit and 64-bit
137
  //       sizeof(long) is often 4 bytes on both 32-bit but 8 bytes on 64-bit
138
  // static_assert(sizeof(long) == 8);
139
140
2
  char* pos;  // mutated by strtol
141
142
2
  errno = 0;
143
2
  long v = strtol(s, &pos, base);
144
145
2
  if (errno == ERANGE) {
146
0
    switch (v) {
147
0
    case LONG_MIN:
148
0
      return false;  // underflow of long, which may be 64 bits
149
0
    case LONG_MAX:
150
0
      return false;  // overflow of long
151
0
    }
152
0
  }
153
154
  // It should ALSO fit in an int, not just a long
155
2
  if (v > INT_MAX) {
156
0
    return false;
157
0
  }
158
2
  if (v < INT_MIN) {
159
0
    return false;
160
0
  }
161
162
2
  const char* end = s + length;
163
2
  if (pos == end) {
164
1
    *result = v;
165
1
    return true;  // strtol() consumed ALL characters.
166
1
  }
167
168
1
  while (pos < end) {
169
1
    if (!IsAsciiWhitespace(*pos)) {
170
1
      return false;  // Trailing non-space
171
1
    }
172
0
    pos++;
173
0
  }
174
175
0
  *result = v;
176
0
  return true;  // Trailing space is OK
177
1
}
178
179
0
bool StringToInt64(const char* s, int length, int base, int64_t* result) {
180
0
  if (length == 0) {
181
0
    return false;  // empty string isn't a valid integer
182
0
  }
183
184
  // These should be the same type
185
0
  static_assert(sizeof(long long) == sizeof(int64_t), "");
186
187
0
  char* pos;  // mutated by strtol
188
189
0
  errno = 0;
190
0
  long long v = strtoll(s, &pos, base);
191
192
0
  if (errno == ERANGE) {
193
0
    switch (v) {
194
0
    case LLONG_MIN:
195
0
      return false;  // underflow
196
0
    case LLONG_MAX:
197
0
      return false;  // overflow
198
0
    }
199
0
  }
200
201
0
  const char* end = s + length;
202
0
  if (pos == end) {
203
0
    *result = v;
204
0
    return true;  // strtol() consumed ALL characters.
205
0
  }
206
207
0
  while (pos < end) {
208
0
    if (!IsAsciiWhitespace(*pos)) {
209
0
      return false;  // Trailing non-space
210
0
    }
211
0
    pos++;
212
0
  }
213
214
0
  *result = v;
215
0
  return true;  // Trailing space is OK
216
0
}
217
218
2
int to_int(BigStr* s, int base) {
219
2
  int i;
220
2
  if (StringToInt(s->data_, len(s), base, &i)) {
221
1
    return i;  // truncated to int
222
1
  } else {
223
1
    throw Alloc<ValueError>();
224
1
  }
225
2
}
226
227
0
BigStr* chr(int i) {
228
  // NOTE: i should be less than 256, in which we could return an object from
229
  // GLOBAL_STR() pool, like StrIter
230
0
  auto result = NewStr(1);
231
0
  result->data_[0] = i;
232
0
  return result;
233
0
}
234
235
0
int ord(BigStr* s) {
236
0
  assert(len(s) == 1);
237
  // signed to unsigned conversion, so we don't get values like -127
238
0
  uint8_t c = static_cast<uint8_t>(s->data_[0]);
239
0
  return c;
240
0
}
241
242
0
bool to_bool(BigStr* s) {
243
0
  return len(s) != 0;
244
0
}
245
246
0
double to_float(int i) {
247
0
  return static_cast<double>(i);
248
0
}
249
250
0
double to_float(BigStr* s) {
251
0
  char* begin = s->data_;
252
0
  char* end = begin + len(s);
253
254
0
  errno = 0;
255
0
  double result = strtod(begin, &end);
256
257
0
  if (errno == ERANGE) {  // error: overflow or underflow
258
0
    if (result >= HUGE_VAL) {
259
0
      return INFINITY;
260
0
    } else if (result <= -HUGE_VAL) {
261
0
      return -INFINITY;
262
0
    } else if (-DBL_MIN <= result && result <= DBL_MIN) {
263
0
      return 0.0;
264
0
    } else {
265
0
      FAIL("Invalid value after ERANGE");
266
0
    }
267
0
  }
268
0
  if (end == begin) {  // error: not a floating point number
269
0
    throw Alloc<ValueError>();
270
0
  }
271
272
0
  return result;
273
0
}
274
275
// e.g. ('a' in 'abc')
276
0
bool str_contains(BigStr* haystack, BigStr* needle) {
277
  // Common case
278
0
  if (len(needle) == 1) {
279
0
    return memchr(haystack->data_, needle->data_[0], len(haystack));
280
0
  }
281
282
0
  if (len(needle) > len(haystack)) {
283
0
    return false;
284
0
  }
285
286
  // General case. TODO: We could use a smarter substring algorithm.
287
288
0
  const char* end = haystack->data_ + len(haystack);
289
0
  const char* last_possible = end - len(needle);
290
0
  const char* p = haystack->data_;
291
292
0
  while (p <= last_possible) {
293
0
    if (memcmp(p, needle->data_, len(needle)) == 0) {
294
0
      return true;
295
0
    }
296
0
    p++;
297
0
  }
298
0
  return false;
299
0
}
300
301
0
BigStr* str_repeat(BigStr* s, int times) {
302
  // Python allows -1 too, and Oil used that
303
0
  if (times <= 0) {
304
0
    return kEmptyString;
305
0
  }
306
0
  int len_ = len(s);
307
0
  int new_len = len_ * times;
308
0
  BigStr* result = NewStr(new_len);
309
310
0
  char* dest = result->data_;
311
0
  for (int i = 0; i < times; i++) {
312
0
    memcpy(dest, s->data_, len_);
313
0
    dest += len_;
314
0
  }
315
0
  return result;
316
0
}
317
318
// for os_path.join()
319
// NOTE(Jesse): Perfect candidate for BoundedBuffer
320
0
BigStr* str_concat3(BigStr* a, BigStr* b, BigStr* c) {
321
0
  int a_len = len(a);
322
0
  int b_len = len(b);
323
0
  int c_len = len(c);
324
325
0
  int new_len = a_len + b_len + c_len;
326
0
  BigStr* result = NewStr(new_len);
327
0
  char* pos = result->data_;
328
329
0
  memcpy(pos, a->data_, a_len);
330
0
  pos += a_len;
331
332
0
  memcpy(pos, b->data_, b_len);
333
0
  pos += b_len;
334
335
0
  memcpy(pos, c->data_, c_len);
336
337
0
  assert(pos + c_len == result->data_ + new_len);
338
339
0
  return result;
340
0
}
341
342
0
BigStr* str_concat(BigStr* a, BigStr* b) {
343
0
  int a_len = len(a);
344
0
  int b_len = len(b);
345
0
  int new_len = a_len + b_len;
346
0
  BigStr* result = NewStr(new_len);
347
0
  char* buf = result->data_;
348
349
0
  memcpy(buf, a->data_, a_len);
350
0
  memcpy(buf + a_len, b->data_, b_len);
351
352
0
  return result;
353
0
}
354
355
//
356
// Comparators
357
//
358
359
32
bool str_equals(BigStr* left, BigStr* right) {
360
  // Fast path for identical strings.  String deduplication during GC could
361
  // make this more likely.  String interning could guarantee it, allowing us
362
  // to remove memcmp().
363
32
  if (left == right) {
364
1
    return true;
365
1
  }
366
367
  // TODO: It would be nice to remove this condition, but I think we need MyPy
368
  // strict None checking for it
369
31
  if (left == nullptr || right == nullptr) {
370
0
    return false;
371
0
  }
372
373
31
  if (left->len_ != right->len_) {
374
1
    return false;
375
1
  }
376
377
30
  return memcmp(left->data_, right->data_, left->len_) == 0;
378
31
}
379
380
0
bool maybe_str_equals(BigStr* left, BigStr* right) {
381
0
  if (left && right) {
382
0
    return str_equals(left, right);
383
0
  }
384
385
0
  if (!left && !right) {
386
0
    return true;  // None == None
387
0
  }
388
389
0
  return false;  // one is None and one is a BigStr*
390
0
}
391
392
7
bool items_equal(BigStr* left, BigStr* right) {
393
7
  return str_equals(left, right);
394
7
}
395
396
7
bool keys_equal(BigStr* left, BigStr* right) {
397
7
  return items_equal(left, right);
398
7
}
399
400
0
bool items_equal(Tuple2<int, int>* t1, Tuple2<int, int>* t2) {
401
0
  return (t1->at0() == t2->at0()) && (t1->at1() == t2->at1());
402
0
}
403
404
0
bool keys_equal(Tuple2<int, int>* t1, Tuple2<int, int>* t2) {
405
0
  return items_equal(t1, t2);
406
0
}
407
408
0
bool items_equal(Tuple2<BigStr*, int>* t1, Tuple2<BigStr*, int>* t2) {
409
0
  return items_equal(t1->at0(), t2->at0()) && (t1->at1() == t2->at1());
410
0
}
411
412
0
bool keys_equal(Tuple2<BigStr*, int>* t1, Tuple2<BigStr*, int>* t2) {
413
0
  return items_equal(t1, t2);
414
0
}
415
416
0
bool str_equals_c(BigStr* s, const char* c_string, int c_len) {
417
  // Needs SmallStr change
418
0
  if (len(s) == c_len) {
419
0
    return memcmp(s->data_, c_string, c_len) == 0;
420
0
  } else {
421
0
    return false;
422
0
  }
423
0
}
424
425
125
bool str_equals0(const char* c_string, BigStr* s) {
426
125
  int n = strlen(c_string);
427
125
  if (len(s) == n) {
428
12
    return memcmp(s->data_, c_string, n) == 0;
429
113
  } else {
430
113
    return false;
431
113
  }
432
125
}
433
434
0
int hash(BigStr* s) {
435
0
  return s->hash(fnv1);
436
0
}
437
438
0
int max(int a, int b) {
439
0
  return std::max(a, b);
440
0
}
441
442
0
int min(int a, int b) {
443
0
  return std::min(a, b);
444
0
}
445
446
0
int max(List<int>* elems) {
447
0
  int n = len(elems);
448
0
  if (n < 1) {
449
0
    throw Alloc<ValueError>();
450
0
  }
451
452
0
  int ret = elems->at(0);
453
0
  for (int i = 0; i < n; ++i) {
454
0
    int cand = elems->at(i);
455
0
    if (cand > ret) {
456
0
      ret = cand;
457
0
    }
458
0
  }
459
460
0
  return ret;
461
0
}