mycpp

Coverage Report

Created: 2025-05-14 21:09

/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
36
void print(BigStr* s) {
14
36
  fputs(s->data_, stdout);  // print until first NUL
15
36
  fputc('\n', stdout);
16
36
}
17
18
4
BigStr* str(int i) {
19
4
  BigStr* s = OverAllocatedStr(kIntBufSize);
20
4
  int length = snprintf(s->data(), kIntBufSize, "%d", i);
21
4
  s->MaybeShrink(length);
22
4
  return s;
23
4
}
24
25
2
BigStr* str(double d) {
26
2
  char buf[64];  // overestimate, but we use snprintf() to be safe
27
28
2
  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
2
  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
2
  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
2
  if (!strchr(buf, '.')) {  // 12345 -> 12345.0
56
1
    buf[length] = '.';
57
1
    buf[length + 1] = '0';
58
1
    buf[length + 2] = '\0';
59
1
  }
60
61
2
  return StrFromC(buf);
62
2
}
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
1
BigStr* intern(BigStr* s) {
74
  // TODO: put in table gHeap.interned_
75
1
  return s;
76
1
}
77
78
// Print quoted string.  Called by StrFormat('%r').
79
// TODO: consider using J8 notation instead, since error messages show that
80
// string.
81
24
BigStr* repr(BigStr* s) {
82
  // Worst case: \0 becomes 4 bytes as '\\x00', and then two quote bytes.
83
24
  int n = len(s);
84
24
  int upper_bound = n * 4 + 2;
85
86
24
  BigStr* result = OverAllocatedStr(upper_bound);
87
88
  // Single quote by default.
89
24
  char quote = '\'';
90
24
  if (memchr(s->data_, '\'', n) && !memchr(s->data_, '"', n)) {
91
6
    quote = '"';
92
6
  }
93
24
  char* p = result->data_;
94
95
  // From PyString_Repr()
96
24
  *p++ = quote;
97
204
  for (int i = 0; i < n; ++i) {
98
180
    unsigned char c = static_cast<unsigned char>(s->data_[i]);
99
180
    if (c == quote || c == '\\') {
100
0
      *p++ = '\\';
101
0
      *p++ = c;
102
180
    } else if (c == '\t') {
103
4
      *p++ = '\\';
104
4
      *p++ = 't';
105
176
    } else if (c == '\n') {
106
7
      *p++ = '\\';
107
7
      *p++ = 'n';
108
169
    } else if (c == '\r') {
109
3
      *p++ = '\\';
110
3
      *p++ = 'r';
111
166
    } else if (0x20 <= c && c < 0x80) {
112
154
      *p++ = c;
113
154
    } else {
114
      // Unprintable becomes \xff.
115
      // TODO: Consider \yff.  This is similar to J8 strings, but we don't
116
      // decode UTF-8.
117
12
      sprintf(p, "\\x%02x", c & 0xff);
118
12
      p += 4;
119
12
    }
120
180
  }
121
24
  *p++ = quote;
122
24
  *p = '\0';
123
124
24
  int length = p - result->data_;
125
24
  result->MaybeShrink(length);
126
24
  return result;
127
24
}
128
129
// Helper functions that don't use exceptions.
130
131
23
bool StringToInt(const char* s, int length, int base, int* result) {
132
23
  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
23
  char* pos;  // mutated by strtol
141
142
23
  errno = 0;
143
23
  long v = strtol(s, &pos, base);
144
145
23
  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
23
  if (v > INT_MAX) {
156
1
    return false;
157
1
  }
158
22
  if (v < INT_MIN) {
159
1
    return false;
160
1
  }
161
162
21
  const char* end = s + length;
163
21
  if (pos == end) {
164
20
    *result = v;
165
20
    return true;  // strtol() consumed ALL characters.
166
20
  }
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
12
bool StringToInt64(const char* s, int length, int base, int64_t* result) {
180
12
  if (length == 0) {
181
1
    return false;  // empty string isn't a valid integer
182
1
  }
183
184
  // These should be the same type
185
11
  static_assert(sizeof(long long) == sizeof(int64_t), "");
186
187
11
  char* pos;  // mutated by strtol
188
189
11
  errno = 0;
190
11
  long long v = strtoll(s, &pos, base);
191
192
11
  if (errno == ERANGE) {
193
2
    switch (v) {
194
1
    case LLONG_MIN:
195
1
      return false;  // underflow
196
1
    case LLONG_MAX:
197
1
      return false;  // overflow
198
2
    }
199
2
  }
200
201
9
  const char* end = s + length;
202
9
  if (pos == end) {
203
5
    *result = v;
204
5
    return true;  // strtol() consumed ALL characters.
205
5
  }
206
207
10
  while (pos < end) {
208
9
    if (!IsAsciiWhitespace(*pos)) {
209
3
      return false;  // Trailing non-space
210
3
    }
211
6
    pos++;
212
6
  }
213
214
1
  *result = v;
215
1
  return true;  // Trailing space is OK
216
4
}
217
218
13
int to_int(BigStr* s, int base) {
219
13
  int i;
220
13
  if (StringToInt(s->data_, len(s), base, &i)) {
221
10
    return i;  // truncated to int
222
10
  } else {
223
3
    throw Alloc<ValueError>();
224
3
  }
225
13
}
226
227
401
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
401
  auto result = NewStr(1);
231
401
  result->data_[0] = i;
232
401
  return result;
233
401
}
234
235
401
int ord(BigStr* s) {
236
401
  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
401
  return c;
240
401
}
241
242
2
bool to_bool(BigStr* s) {
243
2
  return len(s) != 0;
244
2
}
245
246
4
double to_float(int i) {
247
4
  return static_cast<double>(i);
248
4
}
249
250
13
double to_float(BigStr* s) {
251
13
  char* begin = s->data_;
252
13
  char* end = begin + len(s);
253
254
13
  errno = 0;
255
13
  double result = strtod(begin, &end);
256
257
13
  if (errno == ERANGE) {  // error: overflow or underflow
258
4
    if (result >= HUGE_VAL) {
259
1
      return INFINITY;
260
3
    } else if (result <= -HUGE_VAL) {
261
1
      return -INFINITY;
262
2
    } else if (-DBL_MIN <= result && result <= DBL_MIN) {
263
2
      return 0.0;
264
2
    } else {
265
0
      FAIL("Invalid value after ERANGE");
266
0
    }
267
4
  }
268
9
  if (end == begin) {  // error: not a floating point number
269
2
    throw Alloc<ValueError>();
270
2
  }
271
272
7
  return result;
273
9
}
274
275
// e.g. ('a' in 'abc')
276
12
bool str_contains(BigStr* haystack, BigStr* needle) {
277
  // Common case
278
12
  if (len(needle) == 1) {
279
6
    return memchr(haystack->data_, needle->data_[0], len(haystack));
280
6
  }
281
282
6
  if (len(needle) > len(haystack)) {
283
1
    return false;
284
1
  }
285
286
  // General case. TODO: We could use a smarter substring algorithm.
287
288
5
  const char* end = haystack->data_ + len(haystack);
289
5
  const char* last_possible = end - len(needle);
290
5
  const char* p = haystack->data_;
291
292
11
  while (p <= last_possible) {
293
10
    if (memcmp(p, needle->data_, len(needle)) == 0) {
294
4
      return true;
295
4
    }
296
6
    p++;
297
6
  }
298
1
  return false;
299
5
}
300
301
26
BigStr* str_repeat(BigStr* s, int times) {
302
  // Python allows -1 too, and Oil used that
303
26
  if (times <= 0) {
304
3
    return kEmptyString;
305
3
  }
306
23
  int len_ = len(s);
307
23
  int new_len = len_ * times;
308
23
  BigStr* result = NewStr(new_len);
309
310
23
  char* dest = result->data_;
311
417
  for (int i = 0; i < times; i++) {
312
394
    memcpy(dest, s->data_, len_);
313
394
    dest += len_;
314
394
  }
315
23
  return result;
316
26
}
317
318
// for os_path.join()
319
// NOTE(Jesse): Perfect candidate for BoundedBuffer
320
11
BigStr* str_concat3(BigStr* a, BigStr* b, BigStr* c) {
321
11
  int a_len = len(a);
322
11
  int b_len = len(b);
323
11
  int c_len = len(c);
324
325
11
  int new_len = a_len + b_len + c_len;
326
11
  BigStr* result = NewStr(new_len);
327
11
  char* pos = result->data_;
328
329
11
  memcpy(pos, a->data_, a_len);
330
11
  pos += a_len;
331
332
11
  memcpy(pos, b->data_, b_len);
333
11
  pos += b_len;
334
335
11
  memcpy(pos, c->data_, c_len);
336
337
11
  assert(pos + c_len == result->data_ + new_len);
338
339
0
  return result;
340
11
}
341
342
11
BigStr* str_concat(BigStr* a, BigStr* b) {
343
11
  int a_len = len(a);
344
11
  int b_len = len(b);
345
11
  int new_len = a_len + b_len;
346
11
  BigStr* result = NewStr(new_len);
347
11
  char* buf = result->data_;
348
349
11
  memcpy(buf, a->data_, a_len);
350
11
  memcpy(buf + a_len, b->data_, b_len);
351
352
11
  return result;
353
11
}
354
355
//
356
// Comparators
357
//
358
359
229
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
229
  if (left == right) {
364
85
    return true;
365
85
  }
366
367
  // TODO: It would be nice to remove this condition, but I think we need MyPy
368
  // strict None checking for it
369
144
  if (left == nullptr || right == nullptr) {
370
0
    return false;
371
0
  }
372
373
144
  if (left->len_ != right->len_) {
374
7
    return false;
375
7
  }
376
377
137
  return memcmp(left->data_, right->data_, left->len_) == 0;
378
144
}
379
380
3
bool maybe_str_equals(BigStr* left, BigStr* right) {
381
3
  if (left && right) {
382
1
    return str_equals(left, right);
383
1
  }
384
385
2
  if (!left && !right) {
386
1
    return true;  // None == None
387
1
  }
388
389
1
  return false;  // one is None and one is a BigStr*
390
2
}
391
392
70
bool items_equal(BigStr* left, BigStr* right) {
393
70
  return str_equals(left, right);
394
70
}
395
396
22
bool keys_equal(BigStr* left, BigStr* right) {
397
22
  return items_equal(left, right);
398
22
}
399
400
2
bool items_equal(Tuple2<int, int>* t1, Tuple2<int, int>* t2) {
401
2
  return (t1->at0() == t2->at0()) && (t1->at1() == t2->at1());
402
2
}
403
404
2
bool keys_equal(Tuple2<int, int>* t1, Tuple2<int, int>* t2) {
405
2
  return items_equal(t1, t2);
406
2
}
407
408
4
bool items_equal(Tuple2<BigStr*, int>* t1, Tuple2<BigStr*, int>* t2) {
409
4
  return items_equal(t1->at0(), t2->at0()) && (t1->at1() == t2->at1());
410
4
}
411
412
2
bool keys_equal(Tuple2<BigStr*, int>* t1, Tuple2<BigStr*, int>* t2) {
413
2
  return items_equal(t1, t2);
414
2
}
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
74
bool str_equals0(const char* c_string, BigStr* s) {
426
74
  int n = strlen(c_string);
427
74
  if (len(s) == n) {
428
74
    return memcmp(s->data_, c_string, n) == 0;
429
74
  } else {
430
0
    return false;
431
0
  }
432
74
}
433
434
2
int hash(BigStr* s) {
435
2
  return s->hash(fnv1);
436
2
}
437
438
4
int max(int a, int b) {
439
4
  return std::max(a, b);
440
4
}
441
442
0
int min(int a, int b) {
443
0
  return std::min(a, b);
444
0
}
445
446
1
int max(List<int>* elems) {
447
1
  int n = len(elems);
448
1
  if (n < 1) {
449
0
    throw Alloc<ValueError>();
450
0
  }
451
452
1
  int ret = elems->at(0);
453
5
  for (int i = 0; i < n; ++i) {
454
4
    int cand = elems->at(i);
455
4
    if (cand > ret) {
456
1
      ret = cand;
457
1
    }
458
4
  }
459
460
1
  return ret;
461
1
}