mycpp

Coverage Report

Created: 2024-07-09 17:10

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