examples

Coverage Report

Created: 2025-06-14 15:53

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