cheatah
Module

builtins

Python's always-available built-ins — no import needed. The compiler auto-includes this module and resolves bare calls like len("x") to builtins::len. (The math-flavored built-ins abs/min/max/round/pow live in the math module.)

import io
io.print(len("purr"))        # 4
io.print(chr(65), ord("A"))  # A 65
io.print(hex(255))           # 0xff
io.print(int("42") + 1)      # 43

What's here

  • Lengthlen (any sized container or string).

  • Charactersord, chr.

  • Base representationshex, oct, bin.

  • Reprascii (printable-ASCII, escaped, single-quoted).

  • Conversionsbool, int, float (string and numeric overloads).

  • Hashinghash.

  • Growable listsappend(list, x) / xs.append(x) (in-place push).

  • Indexing & slicingindex(seq, i) (seq[i]; negative indices; a string index yields a length-1 string) and slice(seq, lo, hi) (seq[lo:hi]); the compiler lowers seq[i]/seq[i:j] to these.

  • String predicatesstartswith, endswith, contains (usable as methods: s.startswith("…")).

Every template here is constrained by a concept (e.g. the baseline Value, Sized, convertible_to), so misuse fails with a named error, not template spam.

Scalar-returning built-ins (len/ord/to_bool/hash/…) don't allocate; the string-building ones (chr/hex/oct/bin/ascii) allocate their result, and the string-parsing to_int/to_float allocate a temporary std::string.

Per-function docs (parameters, runtime complexity, heap behavior) are in builtins.hpp. Tested in ../tests/builtins_test.cpp; ASan + Valgrind clean via the QA gate (security/run-valgrind.sh).

Classes

Functions

fn len · 2 overloads
std::size_t len(std::string_view s)source#
std::size_t len(const C &c)source#

Length of a C-string / string literal.

Returns the byte length of the view; any embedded NUL bytes are counted (the length comes from the view, not from a terminating NUL).

Parameters
s

the string.

Returns

its byte length.

Complexity

O(1).

Allocation

none.

Compile-run testBuiltinsCompileRun.Len
Performanceheader-inlined to ~sub-nanosecond; the win over CPython is its eliminated ~60 ns per-call interpreter overhead
fn ord · 2 overloads
int ord(std::string_view s)source#
int ord(char c)source#

Code point of the first byte.

Returns the unsigned value of s[0] (0–255), ignoring trailing bytes; an empty string yields 0 rather than throwing.

Parameters
s

a one-character string.

Returns

its byte value (0 if empty).

Complexity

O(1).

Allocation

none.

Compile-run testBuiltinsCompileRun.Ord
Performanceheader-inlined to ~sub-nanosecond; the win over CPython is its eliminated ~60 ns per-call interpreter overhead
fn std::string chr(int codepoint) source#

Character for a code point.

Builds a one-byte string from the low 8 bits of codepoint (it is narrowed to char), so values outside 0–255 wrap modulo 256 rather than producing multi-byte output.

Parameters
codepoint

a byte value.

Returns

the one-character string.

Complexity

O(1).

Allocation

none (1-char small-string optimization).

Compile-run testBuiltinsCompileRun.Chr
Performance2.78 ns/call in cheatah · 87.23 ns/call in CPython 3.12.3 · ≈31.1× faster
fn std::string hex(long long value) source#

Hex representation.

Formats value in base 16 with lowercase digits and a 0x prefix; negatives are rendered as a leading - before the prefix (e.g. -0x1f), and 0 is 0x0.

Parameters
value

the integer.

Returns

"0x…" (with sign).

Complexity

O(log value).

Allocation

allocates the result string, built from a temporary digits buffer.

Compile-run testBuiltinsCompileRun.Hex
Performance23.22 ns/call in cheatah · 89.14 ns/call in CPython 3.12.3 · ≈3.8× faster
fn std::string oct(long long value) source#

Octal representation.

Formats value in base 8 with a 0o prefix; negatives get a leading - before the prefix (e.g. -0o17), and 0 is 0o0.

Parameters
value

the integer.

Returns

"0o…" (with sign).

Complexity

O(log value).

Allocation

allocates the result string, built from a temporary digits buffer.

Compile-run testBuiltinsCompileRun.Oct
Performance24.74 ns/call in cheatah · 93.74 ns/call in CPython 3.12.3 · ≈3.8× faster
fn std::string bin(long long value) source#

Binary representation.

Formats value in base 2 with a 0b prefix; negatives get a leading - before the prefix (e.g. -0b101), and 0 is 0b0.

Parameters
value

the integer.

Returns

"0b…" (with sign).

Complexity

O(log value).

Allocation

allocates the result string, built from a temporary digits buffer.

Compile-run testBuiltinsCompileRun.Bin
Performance74.69 ns/call in cheatah · 99.41 ns/call in CPython 3.12.3 · ≈1.3× faster
fn std::string ascii(std::string_view s) source#

Printable-ASCII repr (non-printables/\\endiskip/' escaped, single-quoted).

Wraps s in single quotes, passing through printable ASCII (bytes 32–126) verbatim while escaping \\endiskip and ' as \\/\' and emitting any other byte as a two-digit \xHH hex escape.

Parameters
s

input.

Returns

the quoted repr.

Complexity

O(n).

Allocation

allocates the result string, plus a temporary ostringstream per escaped byte.

Compile-run testBuiltinsCompileRun.Ascii
Performanceheader-inlined to ~sub-nanosecond; the win over CPython is its eliminated ~60 ns per-call interpreter overhead
fn to_bool · 2 overloads
bool to_bool(std::string_view s)source#
bool to_bool(T x)source#

Truthiness of a string.

Truthy iff non-empty; a whitespace-only or "0"/"false" string is still truthy (only emptiness is false).

Parameters
s

input.

Returns

false iff s is empty.

Complexity

O(1).

Allocation

none.

Performanceheader-inlined to ~sub-nanosecond; the win over CPython is its eliminated ~60 ns per-call interpreter overhead
fn to_int · 2 overloads
long long to_int(std::string_view s)source#
long long to_int(double x)source#

Parse a base-10 integer.

Parses leading whitespace and an optional sign followed by decimal digits via std::stoll; it stops at the first non-digit (so trailing junk is ignored), throws on no parseable digits, and throws on out-of-range values.

Parameters
s

the integer string.

Returns

its value (throws on bad input).

Complexity

O(n).

Allocation

allocates a temporary std::string for the parse.

Performanceheader-inlined to ~sub-nanosecond; the win over CPython is its eliminated ~60 ns per-call interpreter overhead
fn to_float · 2 overloads
double to_float(std::string_view s)source#
double to_float(T x)source#

Parse a float.

Parses leading whitespace and a floating-point literal via std::stod, accepting decimal, scientific (1e9), inf, and nan forms; it stops at the first unparsed character, throws when nothing parses, and throws on overflow.

Parameters
s

a floating-point string.

Returns

its value (throws on bad input).

Complexity

O(n).

Allocation

allocates a temporary std::string for the parse.

Performanceheader-inlined to ~sub-nanosecond; the win over CPython is its eliminated ~60 ns per-call interpreter overhead
fn hash · 2 overloads
std::size_t hash(std::string_view s)source#
std::size_t hash(const T &x)source#

Content hash of a string.

Hashes the bytes via std::hash<std::string_view> (equal contents hash equally); the value is implementation-defined and unstable across runs and compilers (do not persist it).

Parameters
s

input.

Returns

a std::size_t hash.

Complexity

O(n).

Allocation

none.

Note

No

Compile-run test: compile-run coverage is intentionally skipped because the hash value is implementation-defined and has no portable expected stdout.
Performanceheader-inlined to ~sub-nanosecond; the win over CPython is its eliminated ~60 ns per-call interpreter overhead
fn operator== · 4 overloads
bool operator==(const Error &e, const std::string &s)source#
bool operator==(const std::string &s, const Error &e)source#
bool operator==(const Error &e, const char *s)source#
bool operator==(const char *s, const Error &e)source#

Compare an error against a string — by MESSAGE, so e == "boom" reads the way it did when a handler bound a bare string.

Compare e.kind() when you mean the kind.

Parameters
e

the error.

s

the message to compare against.

Returns

true when the error's message is exactly s.

Complexity

O(min(len)).

Allocation

none.

fn std::ostream & operator<<(std::ostream &os, const Error &e) source#

Stream an error as its MESSAGE — the kind would be noise in output that wanted the sentence.

Parameters
os

the destination stream.

e

the error.

Returns

os, for chaining.

Complexity

O(message).

Allocation

none beyond the stream's own.

fn Error current_error() source#

The error currently being handled, normalized to an Error.

Called from inside a catch (...), where throw; re-raises the in-flight exception so it can be inspected by type. This is what lets ONE handler shape cover a raised Error, a std::exception from any C++ library, and a throw of some type we have never heard of — the last of which used to travel straight past every handler and abort the process.

Returns

the in-flight exception as an Error: a raised Error verbatim, a std::out_of_range as kind "index", a std::domain_error as "arithmetic", any other std::exception as "error", and anything else as "unknown".

Complexity

O(1) plus the message copy.

Allocation

copies the kind and message.

fn Finally< F > make_finally(F f) source#

Build a scope guard around f — how finally { … } lowers.

Parameters
f

the callable to run when the enclosing scope ends.

Returns

the guard; keep it alive for the scope you want covered.

Complexity

O(1).

Allocation

moves f into the returned guard.

fn str · 5 overloads
std::string str(const T &value)source#
std::string str(bool b)source#
std::string str(const Error &e)source#
std::string str(signed char v)source#
std::string str(unsigned char v)source#

Python str(): stringify any streamable value (an always-available built-in, so it needs no import — bare str(x) resolves here, like int()/float()/bool()).

Renders value via its operator<< into a fresh ostringstream, so the text matches whatever that stream insertion produces (e.g. default 6-significant-digit float precision), agreeing with io.print/io.str.

Parameters
value

the value to render.

Returns

value formatted as text.

Complexity

O(n) in the output length.

Allocation

allocates the result string (via an ostringstream).

Compile-run testBuiltinsCompileRun.Str
fn double truediv(A a, B b) source#

True division — the cheatah / operator (like Python 3): always floating-point, so 6 / 2 is 3.0, not 3, and integer operands never silently truncate.

Use the // operator (floordiv) when you want integer/floor division.

Parameters
a

numerator.

b

denominator.

Returns

double(a) / double(b).

Complexity

O(1).

Allocation

none.

fn floordiv · 2 overloads
std::common_type_t< A, B > floordiv(A a, B b)source#
double floordiv(A a, B b)source#

Floor division — the cheatah // operator (like Python): the quotient floored toward −∞.

Integer operands give an integer (7 // 2 == 3, -7 // 2 == -4, flooring the way Python does, not truncating toward zero like raw C++); a floating operand gives a floored double (7.0 // 2 == 3.0).

Parameters
a

numerator.

b

denominator; b == 0 throws std::domain_error (integer floor division by zero).

Returns

floor(a / b), integral for integral operands.

Complexity

O(1).

Allocation

none.

fn void append(std::vector< T > &v, U &&x) source#

Append x to list v in place (Python list.append).

Grows v by one, converting x to the list's element type. Usable as a method (xs.append(x)) or a bare call (append(xs, x)); the list is taken by reference, so the caller's list is mutated.

Parameters
v

the list to grow.

x

the value to append.

Complexity

amortized O(1).

Allocation

reallocates v when it outgrows its capacity.

Performanceheader-inlined to ~sub-nanosecond; the win over CPython is its eliminated ~60 ns per-call interpreter overhead
fn bool startswith(std::string_view s, std::string_view prefix) source#

Whether s begins with prefix (Python str.startswith).

Parameters
s

the string.

prefix

the prefix to test.

Returns

true iff s starts with prefix.

Complexity

O(len(prefix)).

Allocation

none.

Performanceheader-inlined to ~sub-nanosecond; the win over CPython is its eliminated ~60 ns per-call interpreter overhead
fn bool endswith(std::string_view s, std::string_view suffix) source#

Whether s ends with suffix (Python str.endswith).

Parameters
s

the string.

suffix

the suffix to test.

Returns

true iff s ends with suffix.

Complexity

O(len(suffix)).

Allocation

none.

Performanceheader-inlined to ~sub-nanosecond; the win over CPython is its eliminated ~60 ns per-call interpreter overhead
fn contains · 3 overloads
bool contains(std::string_view s, std::string_view sub)source#
bool contains(const std::unordered_map< K, V, H, E, A > &d, const Key &key)source#
bool contains(const std::vector< T, A > &xs, const Value &value)source#

Whether sub occurs anywhere in s (Python sub in s).

Parameters
s

the string to search.

sub

the substring to find.

Returns

true iff sub is a substring of s.

Complexity

O(len(s) · len(sub)) worst case.

Allocation

none.

Performanceheader-inlined to ~sub-nanosecond; the win over CPython is its eliminated ~60 ns per-call interpreter overhead
fn mod · 2 overloads
std::common_type_t< A, B > mod(A a, B b)source#
double mod(A a, B b)source#

Python FLOOR-mod for integers: the result takes the DIVISOR's sign (-7 % 3 == 2), unlike raw C++ %.

Backs the % operator.

Parameters
a

the dividend.

b

the divisor; b == 0 throws std::domain_error (integer modulo by zero).

Returns

a mod b with the sign of b (Python floor-mod semantics).

Complexity

O(1).

Allocation

none.

Compile-run testLangFeatures.Modulo
fn index · 7 overloads
std::string index(const std::string &s, long long i)source#
const std::decay_t< decltype(c[0])> & index(const C &c, long long i)source#
bool index(const std::vector< bool > &c, long long i)source#
const V & index(const std::unordered_map< K, V, H, E, A > &m, const Key &key)source#
T index(const ::cheatah::fixarray::Fixed< T, Dims... > &v, Ix i)source#
T index(const ::cheatah::fixarray::Fixed< T, Dims... > &m, I i, J j)source#
T index(const ::cheatah::ndarray::basic_ndarray< T > &a, First first, Ix... rest)source#

Element at i of a string — a length-1 string (Python s[i]).

Negative i counts from the end; out-of-range throws std::out_of_range.

Parameters
s

the string.

i

the index (may be negative).

Returns

the one-character string at i.

Complexity

O(1).

Allocation

none (1-char small-string optimization).

Performanceheader-inlined to ~sub-nanosecond; the win over CPython is its eliminated ~60 ns per-call interpreter overhead
fn slice · 2 overloads
std::string slice(const std::string &s, long long lo, long long hi)source#
std::vector< std::decay_t< decltype(c[0])> > slice(const C &c, long long lo, long long hi)source#

Substring s[lo:hi] (Python slice semantics: clamped, negatives from the end).

Parameters
s

the string.

lo

start index (default 0 at the call site).

hi

end index, or slice_end for "to the end".

Returns

the slice (empty if lo >= hi after clamping).

Complexity

O(hi-lo).

Allocation

the result string.

Performanceheader-inlined to ~sub-nanosecond; the win over CPython is its eliminated ~60 ns per-call interpreter overhead

Constants & variables

var const char * kErrorKindError source#

Conventional kinds raised from the language core. Libraries are free to define their own.

raise "msg" — unclassified

var const char * kErrorKindIndex source#

subscript out of range

var const char * kErrorKindKey source#

dict key absent

var const char * kErrorKindArithmetic source#

divide / modulo by zero

var const char * kErrorKindUnknown source#

a throw of a type we cannot inspect

var long long slice_end source#

Sentinel for an omitted slice upper bound (s[a:]): "to the end".