examples

Coverage Report

Created: 2025-05-01 23:13

/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
1.27k
void print(BigStr* s) {
14
1.27k
  fputs(s->data_, stdout);  // print until first NUL
15
1.27k
  fputc('\n', stdout);
16
1.27k
}
17
18
35
BigStr* str(int i) {
19
35
  BigStr* s = OverAllocatedStr(kIntBufSize);
20
35
  int length = snprintf(s->data(), kIntBufSize, "%d", i);
21
35
  s->MaybeShrink(length);
22
35
  return s;
23
35
}
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
25
BigStr* repr(BigStr* s) {
82
  // Worst case: \0 becomes 4 bytes as '\\x00', and then two quote bytes.
83
25
  int n = len(s);
84
25
  int upper_bound = n * 4 + 2;
85
86
25
  BigStr* result = OverAllocatedStr(upper_bound);
87
88
  // Single quote by default.
89
25
  char quote = '\'';
90
25
  if (memchr(s->data_, '\'', n) && !memchr(s->data_, '"', n)) {
91
0
    quote = '"';
92
0
  }
93
25
  char* p = result->data_;
94
95
  // From PyString_Repr()
96
25
  *p++ = quote;
97
167
  for (int i = 0; i < n; ++i) {
98
142
    unsigned char c = static_cast<unsigned char>(s->data_[i]);
99
142
    if (c == quote || c == '\\') {
100
0
      *p++ = '\\';
101
0
      *p++ = c;
102
142
    } else if (c == '\t') {
103
1
      *p++ = '\\';
104
1
      *p++ = 't';
105
141
    } else if (c == '\n') {
106
2
      *p++ = '\\';
107
2
      *p++ = 'n';
108
139
    } else if (c == '\r') {
109
1
      *p++ = '\\';
110
1
      *p++ = 'r';
111
138
    } else if (0x20 <= c && c < 0x80) {
112
138
      *p++ = c;
113
138
    } 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
142
  }
121
25
  *p++ = quote;
122
25
  *p = '\0';
123
124
25
  int length = p - result->data_;
125
25
  result->MaybeShrink(length);
126
25
  return result;
127
25
}
128
129
// Helper functions that don't use exceptions.
130
131
18
bool StringToInt(const char* s, int length, int base, int* result) {
132
18
  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
18
  char* pos;  // mutated by strtol
141
142
18
  errno = 0;
143
18
  long v = strtol(s, &pos, base);
144
145
18
  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
18
  if (v > INT_MAX) {
156
0
    return false;
157
0
  }
158
18
  if (v < INT_MIN) {
159
0
    return false;
160
0
  }
161
162
18
  const char* end = s + length;
163
18
  if (pos == end) {
164
18
    *result = v;
165
18
    return true;  // strtol() consumed ALL characters.
166
18
  }
167
168
0
  while (pos < end) {
169
0
    if (!IsAsciiWhitespace(*pos)) {
170
0
      return false;  // Trailing non-space
171
0
    }
172
0
    pos++;
173
0
  }
174
175
0
  *result = v;
176
0
  return true;  // Trailing space is OK
177
0
}
178
179
1
bool StringToInt64(const char* s, int length, int base, int64_t* result) {
180
1
  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
1
  static_assert(sizeof(long long) == sizeof(int64_t), "");
186
187
1
  char* pos;  // mutated by strtol
188
189
1
  errno = 0;
190
1
  long long v = strtoll(s, &pos, base);
191
192
1
  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
1
  const char* end = s + length;
202
1
  if (pos == end) {
203
1
    *result = v;
204
1
    return true;  // strtol() consumed ALL characters.
205
1
  }
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
15
int to_int(BigStr* s, int base) {
219
15
  int i;
220
15
  if (StringToInt(s->data_, len(s), base, &i)) {
221
15
    return i;  // truncated to int
222
15
  } else {
223
0
    throw Alloc<ValueError>();
224
0
  }
225
15
}
226
227
542
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
542
  auto result = NewStr(1);
231
542
  result->data_[0] = i;
232
542
  return result;
233
542
}
234
235
30
int ord(BigStr* s) {
236
30
  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
30
  return c;
240
30
}
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
60
bool str_contains(BigStr* haystack, BigStr* needle) {
277
  // Common case
278
60
  if (len(needle) == 1) {
279
60
    return memchr(haystack->data_, needle->data_[0], len(haystack));
280
60
  }
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
2
BigStr* str_repeat(BigStr* s, int times) {
302
  // Python allows -1 too, and Oil used that
303
2
  if (times <= 0) {
304
0
    return kEmptyString;
305
0
  }
306
2
  int len_ = len(s);
307
2
  int new_len = len_ * times;
308
2
  BigStr* result = NewStr(new_len);
309
310
2
  char* dest = result->data_;
311
15
  for (int i = 0; i < times; i++) {
312
13
    memcpy(dest, s->data_, len_);
313
13
    dest += len_;
314
13
  }
315
2
  return result;
316
2
}
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
140
BigStr* str_concat(BigStr* a, BigStr* b) {
343
140
  int a_len = len(a);
344
140
  int b_len = len(b);
345
140
  int new_len = a_len + b_len;
346
140
  BigStr* result = NewStr(new_len);
347
140
  char* buf = result->data_;
348
349
140
  memcpy(buf, a->data_, a_len);
350
140
  memcpy(buf + a_len, b->data_, b_len);
351
352
140
  return result;
353
140
}
354
355
//
356
// Comparators
357
//
358
359
45
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
45
  if (left == right) {
364
17
    return true;
365
17
  }
366
367
  // TODO: It would be nice to remove this condition, but I think we need MyPy
368
  // strict None checking for it
369
28
  if (left == nullptr || right == nullptr) {
370
0
    return false;
371
0
  }
372
373
28
  if (left->len_ != right->len_) {
374
3
    return false;
375
3
  }
376
377
25
  return memcmp(left->data_, right->data_, left->len_) == 0;
378
28
}
379
380
4
bool maybe_str_equals(BigStr* left, BigStr* right) {
381
4
  if (left && right) {
382
2
    return str_equals(left, right);
383
2
  }
384
385
2
  if (!left && !right) {
386
0
    return true;  // None == None
387
0
  }
388
389
2
  return false;  // one is None and one is a BigStr*
390
2
}
391
392
15
bool items_equal(BigStr* left, BigStr* right) {
393
15
  return str_equals(left, right);
394
15
}
395
396
12
bool keys_equal(BigStr* left, BigStr* right) {
397
12
  return items_equal(left, right);
398
12
}
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
5
bool str_equals_c(BigStr* s, const char* c_string, int c_len) {
417
  // Needs SmallStr change
418
5
  if (len(s) == c_len) {
419
5
    return memcmp(s->data_, c_string, c_len) == 0;
420
5
  } else {
421
0
    return false;
422
0
  }
423
5
}
424
425
0
bool str_equals0(const char* c_string, BigStr* s) {
426
0
  int n = strlen(c_string);
427
0
  if (len(s) == n) {
428
0
    return memcmp(s->data_, c_string, n) == 0;
429
0
  } else {
430
0
    return false;
431
0
  }
432
0
}
433
434
0
int hash(BigStr* s) {
435
0
  return s->hash(fnv1);
436
0
}
437
438
800
int max(int a, int b) {
439
800
  return std::max(a, b);
440
800
}
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
}