Files
zern/src/std/std.zr
2026-03-12 17:50:01 +01:00

805 lines
20 KiB
Plaintext

func panic[msg: str] : void
io.print("PANIC: ")
io.println(msg)
(0 / 0) // crashes program which is kinda better since you get a gdb backtrace
os.exit(1)
const MEM_BLOCK_SIZE = 24
struct mem.Block
size: i64
free: bool
next: mem.Block
func mem._align[x: i64] : i64
return (x + 7) & -8
func mem._split_block[blk: mem.Block, needed: i64] : void
if blk->size >= needed + MEM_BLOCK_SIZE + 8
let new_blk: mem.Block = blk + MEM_BLOCK_SIZE + needed
new_blk->size = blk->size - needed - MEM_BLOCK_SIZE
new_blk->free = true
new_blk->next = blk->next
blk->size = needed
blk->next = new_blk
if mem.read64(_builtin_heap_tail()) == blk
mem.write64(_builtin_heap_tail(), new_blk)
func mem._request_space[size: i64] : mem.Block
let needed: i64 = size + MEM_BLOCK_SIZE
let alloc_size: i64 = (needed + 4095) & -4096
// PROT_READ | PROT_WRITE = 3
// MAP_PRIVATE | MAP_ANONYMOUS = 34
// fd = -1, offset = 0
let blk: mem.Block = _builtin_syscall(SYS_mmap, 0, alloc_size, 3, 34, -1, 0)
if blk == -1
return 0
blk->size = alloc_size - MEM_BLOCK_SIZE
blk->free = false
blk->next = 0
let tail: mem.Block = mem.read64(_builtin_heap_tail())
if tail
tail->next = blk
mem.write64(_builtin_heap_tail(), blk)
return blk
func mem._coalesce[] : void
let cur: mem.Block = mem.read64(_builtin_heap_head())
let prev: mem.Block = 0
while cur
let next: mem.Block = cur->next
let expected_next: mem.Block = cur + MEM_BLOCK_SIZE + cur->size
if cur->free && next && next->free && expected_next == next
cur->size = cur->size + MEM_BLOCK_SIZE + next->size
cur->next = next->next
if !cur->next
mem.write64(_builtin_heap_tail(), cur)
continue
let block_total: i64 = cur->size + MEM_BLOCK_SIZE
if cur->free && (cur & 4095) == 0 && (block_total & 4095) == 0
if prev
prev->next = cur->next
if !cur->next
mem.write64(_builtin_heap_tail(), prev)
else
mem.write64(_builtin_heap_head(), cur->next)
if !cur->next
mem.write64(_builtin_heap_tail(), 0)
let saved_next: mem.Block = cur->next
_builtin_syscall(11, cur, block_total)
cur = saved_next
continue
prev = cur
cur = cur->next
func mem.alloc[size: i64] : ptr
if size == 0
return 0
size = mem._align(size)
let cur: mem.Block = mem.read64(_builtin_heap_head())
while cur
if cur->free && cur->size >= size
mem._split_block(cur, size)
cur->free = false
return cur + MEM_BLOCK_SIZE
cur = cur->next
let blk: mem.Block = mem._request_space(size)
if !blk
return 0
if !mem.read64(_builtin_heap_head())
mem.write64(_builtin_heap_head(), blk)
mem._split_block(blk, size)
return blk + MEM_BLOCK_SIZE
func mem.free[x: ptr] : void
if !x
return 0
let blk: mem.Block = x - MEM_BLOCK_SIZE
blk->free = true
mem._coalesce()
func mem.realloc[x: ptr, new_size: i64] : ptr
if !x
return mem.alloc(new_size)
if new_size == 0
mem.free(x)
return 0
new_size = mem._align(new_size)
let blk: mem.Block = x - MEM_BLOCK_SIZE
if blk->size >= new_size
mem._split_block(blk, new_size)
return x
let next: mem.Block = blk->next
let expected_next: mem.Block = blk + MEM_BLOCK_SIZE + blk->size
if next && next->free && expected_next == next
let combined: i64 = blk->size + MEM_BLOCK_SIZE + next->size
if combined >= new_size
blk->size = combined
blk->next = next->next
if !blk->next
mem.write64(_builtin_heap_tail(), blk)
mem._split_block(blk, new_size)
return x
let new_ptr: ptr = mem.alloc(new_size)
if !new_ptr
return 0
mem.copy(x, new_ptr, math.min(blk->size, new_size))
mem.free(x)
return new_ptr
func mem.zero_and_free[x: ptr, size: i64] : void
mem.zero(x, size)
mem.free(x)
func mem.zero[x: ptr, size: i64] : void
for i in 0..size
x[i] = 0
func mem.copy[src: ptr, dst: ptr, n: i64] : void
for i in 0..n
dst[i] = src[i]
func mem.read8[x: ptr] : u8
return x[0]
func mem.read16[x: ptr] : i64
return x[0] | (x[1] << 8)
func mem.read32[x: ptr] : i64
return x[0] | (x[1] << 8) | (x[2] << 16) | (x[3] << 24)
func mem.read64[x: ptr] : i64
return _builtin_read64(x)
func mem.write32[x: ptr, d: i64] : void
x[0] = d & 0xff
x[1] = (d >> 8) & 0xff
x[2] = (d >> 16) & 0xff
x[3] = (d >> 24) & 0xff
func mem.write64[x: ptr, d: i64] : void
_builtin_set64(x, d)
func io.print_sized[x: str, size: i64] : void
_builtin_syscall(SYS_write, 1, x, size)
func io.print[x: str] : void
io.print_sized(x, str.len(x))
func io.println[x: str] : void
io.print(x)
io.print("\n")
func io.print_char[x: u8] : void
io.print_sized(^x, 1)
func io.print_bool[x: bool] : void
if x
io.print("true")
else
io.print("false")
func io.print_i64[x: i64] : void
let s: str = str.from_i64(x)
io.print(s)
mem.free(s)
func io.print_i64_hex[x: i64] : void
let s: str = str.hex_from_i64(x)
io.print(s)
mem.free(s)
func io.println_i64[x: i64] : void
let s: str = str.from_i64(x)
io.println(s)
mem.free(s)
func io.read_char[] : u8
let c: u8 = 0
_builtin_syscall(SYS_read, 0, ^c, 1)
return c
func io.read_line[]: str
let MAX_SIZE = 60000
let buffer: str = mem.alloc(MAX_SIZE + 1)
let n: i64 = _builtin_syscall(SYS_read, 0, buffer, MAX_SIZE)
if n < 0
mem.free(buffer)
return ""
buffer[n] = 0
return buffer
func io.file_exists[path: str] : bool
return _builtin_syscall(SYS_faccessat, -100, path, 0, 0) == 0
func io.read_file[path: str] : str
let fd: i64 = _builtin_syscall(SYS_openat, -100, path, 0, 0)
if fd <= 0
panic("failed to open file") // TODO
let size: i64 = _builtin_syscall(SYS_lseek, fd, 0, 2)
_builtin_syscall(SYS_lseek, fd, 0, 0)
let buffer: str = mem.alloc(size + 1)
let n: i64 = _builtin_syscall(SYS_read, fd, buffer, size)
_builtin_syscall(SYS_close, fd)
buffer[n] = 0
return buffer
struct io.Buffer
data: ptr
size: i64
func io.read_binary_file[path: str] : io.Buffer
let fd: i64 = _builtin_syscall(SYS_openat, -100, path, 0, 0)
if fd < 0
panic("failed to open file") // TODO
let buffer: io.Buffer = new io.Buffer
buffer->size = _builtin_syscall(SYS_lseek, fd, 0, 2)
_builtin_syscall(SYS_lseek, fd, 0, 0)
buffer->data = mem.alloc(buffer->size)
_builtin_syscall(SYS_read, fd, buffer->data, buffer->size)
_builtin_syscall(SYS_close, fd)
return buffer
func io.write_file[path: str, content: str] : void
let fd: i64 = _builtin_syscall(SYS_openat, -100, path, 0x241, 0o644)
if fd < 0
panic("failed to open file") // TODO
_builtin_syscall(SYS_write, fd, content, str.len(content))
_builtin_syscall(SYS_close, fd)
func io.write_binary_file[path: str, content: ptr, size: i64] : void
let fd: i64 = _builtin_syscall(SYS_openat, -100, path, 0x241, 0o644)
if fd < 0
panic("failed to open file") // TODO
_builtin_syscall(SYS_write, fd, content, size)
_builtin_syscall(SYS_close, fd)
func str.len[s: str] : i64
let i = 0
while s[i]
i = i + 1
return i
func str.make_copy[s: str] : str
let size: i64 = str.len(s) + 1
let dup: str = mem.alloc(size)
mem.copy(s, dup, size)
return dup
func str.equal[a: str, b: str] : bool
let i = 0
while a[i] != 0 && b[i] != 0
if a[i] != b[i]
return false
i = i + 1
return a[i] == b[i]
func str.is_whitespace[x: u8] : bool
return x == ' ' || x == 10 || x == 13 || x == 9
func str.is_digit[x: u8] : bool
return x >= '0' && x <= '9'
func str.is_hex_digit[x: u8] : bool
return (x >= '0' && x <= '9') || (x >= 'a' && x <= 'f') || (x >= 'A' && x <= 'F')
func str.is_lowercase[x: u8] : bool
return x >= 'a' && x <= 'z'
func str.is_uppercase[x: u8] : bool
return x >= 'A' && x <= 'Z'
func str.is_letter[x: u8] : bool
return str.is_uppercase(x) || str.is_lowercase(x)
func str.is_alphanumeric[x: u8] : bool
return str.is_letter(x) || str.is_digit(x)
func str.concat[a: str, b: str] : str
let a_len: i64 = str.len(a)
let b_len: i64 = str.len(b)
let out: str = mem.alloc(a_len + b_len + 1)
mem.copy(a, out, a_len)
mem.copy(b, out + a_len, b_len)
out[a_len + b_len] = 0
return out
func str.contains[haystack: str, needle: str] : bool
return str.find(haystack, needle) != -1
func str.find[haystack: str, needle: str] : i64
let haystack_len: i64 = str.len(haystack)
let needle_len: i64 = str.len(needle)
if needle_len == 0
return 0
for i in 0..(haystack_len - needle_len + 1)
let match: bool = true
for j in 0..needle_len
if haystack[i + j] != needle[j]
match = false
break
if match
return i
return -1
func str.substr[s: str, start: i64, length: i64] : str
if start < 0 || length < 0 || start + length > str.len(s)
panic("str.substr out of bounds")
let out: str = mem.alloc(length + 1)
mem.copy(s + start, out, length)
out[length] = 0
return out
func str.trim[s: str] : str
let len: i64 = str.len(s)
if len == 0
return ""
let start = 0
let end: i64 = len - 1
while start <= end && str.is_whitespace(s[start])
start = start + 1
while end >= start && str.is_whitespace(s[end])
end = end - 1
return str.substr(s, start, end - start + 1)
func str.split[haystack: str, needle: str]: Array
let haystack_len: i64 = str.len(haystack)
let needle_len: i64 = str.len(needle)
let result: Array = []
if !needle_len
if !haystack_len
return result
else
for i in 0..haystack_len
array.push(result, str.substr(haystack, i, 1))
return result
let start = 0
let i = 0
while i < haystack_len
if i <= haystack_len - needle_len
let match: bool = true
for j in 0..needle_len
if haystack[i + j] != needle[j]
match = false
break
if match
array.push(result, str.substr(haystack, start, i - start))
start = i + needle_len
i = i + needle_len
continue
i = i + 1
array.push(result, str.substr(haystack, start, haystack_len - start))
return result
func str.reverse[s: str] : str
let len: i64 = str.len(s)
let out: str = mem.alloc(len + 1)
for i in 0..len
out[i] = s[len - i - 1]
out[len] = 0
return out
// not sure this covers all the wacky edge cases
func str.from_i64[n: i64] : str
if n == 0
let out: str = mem.alloc(2)
out[0] = '0'
out[1] = 0
return out
let neg: bool = n < 0
if neg
n = -n
let buf: str = mem.alloc(21) // enough to fit -MAX_I64
let i = 0
while n > 0
let d: u8 = n % 10
buf[i] = '0' + d
n = n / 10
i = i + 1
if neg
buf[i] = '-'
i = i + 1
buf[i] = 0
let s: str = str.reverse(buf)
mem.free(buf)
return s
func str.hex_from_i64[n: i64] : str
let hex_chars: str = "0123456789abcdef"
if n == 0
let out: str = mem.alloc(2)
out[0] = '0'
out[1] = 0
return out
let buf: str = mem.alloc(17)
let len = 0
while n > 0
buf[len] = hex_chars[n & 15]
n = n >> 4
len = len + 1
let out: str = mem.alloc(len + 1)
let j = 0
while j < len
out[j] = buf[len - 1 - j]
j = j + 1
out[len] = 0
return out
func str.from_char[c: u8] : str
let s: str = mem.alloc(2)
s[0] = c
s[1] = 0
return s
func str.parse_i64[s: str] : i64
let len: i64 = str.len(s)
let i = 0
let sign = 1
if i < len && s[i] == '-'
sign = -1
i = i + 1
let num = 0
while i < len
let d: u8 = s[i]
if d < '0' || d > '9'
break
num = num * 10 + (d - '0')
i = i + 1
return num * sign
func str.hex_encode[s: str, s_len: i64] : str
let hex_chars: str = "0123456789abcdef"
let j = 0
let out: str = mem.alloc(s_len * 2 + 1)
for i in 0..s_len
let high: u8 = (s[i] >> 4) & 15
let low: u8 = s[i] & 15
out[j] = hex_chars[high]
out[j + 1] = hex_chars[low]
j = j + 2
out[j] = 0
return out
func str._hex_digit_to_int[d: u8] : i64
if d >= 'a' && d <= 'f'
return d - 'a' + 10
if d >= 'A' && d <= 'F'
return d - 'A' + 10
return d - '0'
func str.hex_decode[s: str] : str
let s_len: i64 = str.len(s)
let i = 0
let j = 0
let out: str = mem.alloc(s_len / 2 + 1)
while i < s_len
out[j] = str._hex_digit_to_int(s[i]) * 16 + str._hex_digit_to_int(s[i + 1])
i = i + 2
j = j + 1
out[j] = 0
return out
func math.gcd[a: i64, b: i64] : i64
while b != 0
let tmp: i64 = b
b = a % b
a = tmp
return a
func math.min[a: i64, b: i64] : i64
if a < b
return a
return b
func math.max[a: i64, b: i64] : i64
if a > b
return a
return b
func math.abs[n: i64] : i64
if n < 0
return -n
return n
func math.sign[n: i64] : i64
if n < 0
return -1
else if n > 0
return 1
else
return 0
func math.pow[b: i64, e: i64] : i64
let out = 1
for i in 0..e
out = out * b
return out
func math.lcm[a: i64, b: i64] : i64
return (a * b) / math.gcd(a, b)
func math.isqrt[n: i64] : i64
if n < 0
panic("negative number passed to math.isqrt")
if n == 0 || n == 1
return n
let guess: i64 = n
let next_guess: i64 = (guess + n / guess) / 2
while next_guess < guess
guess = next_guess
next_guess = (guess + n / guess) / 2
return guess
func math.is_prime[n: i64]: bool
if n <= 1
return false
if n == 2 || n == 3
return true
if n % 2 == 0 || n % 3 == 0
return false
let i = 5
while i * i <= n
if n % i == 0 || n % (i + 2) == 0
return false
i = i + 6
return true
struct Array
data: ptr
size: i64
capacity: i64
func array.new[] : Array
return new Array
func array.nth[xs: Array, n: i64] : any
if n < 0 || n >= xs->size
panic("array.nth out of bounds")
return mem.read64(xs->data + n * 8)
func array.set[xs: Array, n: i64, x: any] : void
if n < 0 || n >= xs->size
panic("array.set out of bounds")
mem.write64(xs->data + n * 8, x)
func array.push[xs: Array, x: any] : void
if xs->size == xs->capacity
let new_capacity = 4
if xs->capacity != 0
new_capacity = xs->capacity * 2
xs->data = mem.realloc(xs->data, new_capacity * 8)
xs->capacity = new_capacity
mem.write64(xs->data + xs->size * 8, x)
xs->size = xs->size + 1
func array.free[xs: Array] : void
if xs->data != 0
mem.free(xs->data)
mem.free(xs)
func array.pop[xs: Array] : any
if xs->size == 0
panic("array.pop on empty array")
let x: any = array.nth(xs, xs->size - 1)
xs->size = xs->size - 1
return x
func array.slice[xs: Array, start: i64, length: i64] : Array
if start < 0 || length < 0 || start + length > xs->size
panic("array.slice out of bounds")
let new_array: Array = []
for i in 0..length
array.push(new_array, array.nth(xs, start + i))
return new_array
func array.concat[a: Array, b: Array] : Array
let new_array: Array = []
for i in 0..a->size
array.push(new_array, array.nth(a, i))
for i in 0..b->size
array.push(new_array, array.nth(b, i))
return new_array
func alg.quicksort[arr: Array] : void
alg._do_quicksort(arr, 0, arr->size - 1)
func alg._do_quicksort[arr: Array, low: i64, high: i64] : void
if low < high
let i: i64 = alg._partition(arr, low, high)
alg._do_quicksort(arr, low, i - 1)
alg._do_quicksort(arr, i + 1, high)
func alg._partition[arr: Array, low: i64, high: i64] : i64
let pivot: i64 = array.nth(arr, high)
let i: i64 = low - 1
for j in (low)..high
if array.nth(arr, j) <= pivot
i = i + 1
let temp: i64 = array.nth(arr ,i)
array.set(arr, i, array.nth(arr, j))
array.set(arr, j, temp)
let temp: i64 = array.nth(arr, i + 1)
array.set(arr, i + 1, array.nth(arr, high))
array.set(arr, high, temp)
return i + 1
func alg.count[arr: Array, item: any] : i64
let count = 0
for i in 0..arr->size
if array.nth(arr, i) == item
count = count + 1
return count
func alg.map[arr: Array, fn: ptr] : Array
let out: Array = []
for i in 0..arr->size
array.push(out, fn(array.nth(arr, i)))
return out
func alg.filter[arr: Array, fn: ptr] : Array
let out: Array = []
for i in 0..arr->size
if fn(array.nth(arr, i))
array.push(out, array.nth(arr, i))
return out
func alg.reduce[arr: Array, fn: ptr, acc: any] : any
for i in 0..arr->size
acc = fn(acc, array.nth(arr, i))
return acc
func os.exit[code: i64] : void
_builtin_syscall(SYS_exit, code)
func os.getpid[] : i64
return _builtin_syscall(SYS_getpid)
func os.sleep[ms: i64] : void
if ms < 0
panic("negative time passed to os.sleep")
// TODO: we really shouldnt need a heap allocation to sleep
let req: os.Timeval = new os.Timeval
req->tv_sec = ms / 1000
// yes, we should have a os.Timespec with tv_nsec but this works for now
req->tv_usec = (ms % 1000) * 1000000
_builtin_syscall(SYS_nanosleep, req, 0)
mem.free(req)
func os.urandom[n: i64]: ptr
let buffer: ptr = mem.alloc(n)
let fd: i64 = _builtin_syscall(SYS_openat, -100, "/dev/urandom", 0, 0)
_builtin_syscall(SYS_read, fd, buffer, n)
_builtin_syscall(SYS_close, fd)
return buffer
func os.urandom_i64[]: i64
let buffer: ptr = os.urandom(8)
let n: i64 = mem.read64(buffer)
mem.free(buffer)
return n
struct os.Timeval
tv_sec: i64
tv_usec: i64
func os.time[] : i64
// TODO: we really shouldnt need a heap allocation to check the time
let tv: os.Timeval = new os.Timeval
_builtin_syscall(SYS_gettimeofday, tv, 0)
let out: i64 = tv->tv_sec * 1000 + tv->tv_usec / 1000
mem.free(tv)
return out
// voodoo magic
func os.run_shell_command[command: str] : i64
let pid: i64 = _builtin_syscall(SYS_fork)
if pid == 0
let argv: Array = ["sh", "-c", command, 0] // gets freed after child process exits
_builtin_syscall(SYS_execve, "/bin/sh", argv->data, _builtin_environ())
_builtin_syscall(SYS_exit, 1)
else
let status = 0
let wp: i64 = _builtin_syscall(SYS_wait4, pid, ^status, 0, 0)
if wp == -1
return -1
let st: i64 = status & 0xffffffff
if (st & 0x7f) == 0
return (st >> 8) & 0xff
else
return -(st & 0x7f)
func os.list_directory[path: str] : Array
let fd: i64 = _builtin_syscall(SYS_openat, -100, path, 0, 0)
if fd < 0
return []
let files: Array = []
let buf: ptr = mem.alloc(1024)
while true
let n: i64 = _builtin_syscall(SYS_getdents64, fd, buf, 1024)
if n <= 0
break
let pos = 0
while pos < n
let len: i64 = mem.read16(buf + pos + 16)
let name: str = buf + pos + 19
if name[0]
let skip: bool = false
// skip if name is exactly '.' or '..'
if name[0] == '.'
if name[1] == 0
skip = true
else if name[1] == '.'
if name[2] == 0
skip = true
if !skip
array.push(files, str.make_copy(name))
pos = pos + len
mem.free(buf)
_builtin_syscall(SYS_close, fd)
return files