Compare commits

..

7 Commits

Author SHA1 Message Date
165b5844de remove type hints from declarations 2026-07-17 16:14:08 +02:00
45171f688c more fuzzing, recursion, prevent including block devices, utf8 fix 2026-07-17 14:21:29 +02:00
1471c229c2 generic types, any -> opaque 2026-07-17 11:44:05 +02:00
af08d1888a real relative imports 2026-07-15 18:26:28 +02:00
9bbd382e10 http server 2026-07-07 19:40:25 +02:00
aea9ce911a std json parser 2026-07-05 15:22:50 +02:00
873aa3e1cc normal destructuring with one line changed 2026-07-01 17:01:47 +02:00
56 changed files with 885 additions and 501 deletions

43
Cargo.lock generated
View File

@@ -2,49 +2,6 @@
# It is not intended for manual editing. # It is not intended for manual editing.
version = 4 version = 4
[[package]]
name = "cc"
version = "1.2.65"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e228eec9be7c17ccb640b59b36a5cd805ea2a564a4c5e162c2f659fea30d3b96"
dependencies = [
"find-msvc-tools",
"shlex",
]
[[package]]
name = "find-msvc-tools"
version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
[[package]]
name = "libmimalloc-sys"
version = "0.1.49"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a45a52f43e1c16f667ccfe4dd8c85b7f7c204fd5e3bf46c5b0db9a5c3c0b8e9"
dependencies = [
"cc",
]
[[package]]
name = "mimalloc"
version = "0.1.52"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2d4139bb28d14ad1facf21d5eb8825051b326e172d216b39f6d31df53cc97862"
dependencies = [
"libmimalloc-sys",
]
[[package]]
name = "shlex"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
[[package]] [[package]]
name = "zern" name = "zern"
version = "0.3.0" version = "0.3.0"
dependencies = [
"mimalloc",
]

View File

@@ -3,9 +3,3 @@ name = "zern"
version = "0.3.0" version = "0.3.0"
edition = "2024" edition = "2024"
license = "BSD-2-Clause" license = "BSD-2-Clause"
[dependencies]
mimalloc = { version = "0.1.52", optional = true }
[features]
mimalloc = ["dep:mimalloc"]

View File

@@ -7,10 +7,12 @@ A very cool language
* Compiles to x86-64 Assembly * Compiles to x86-64 Assembly
* No libc required! * No libc required!
* Produces tiny static executables (11KB for `hello.zr`) * Produces tiny static executables (11KB for `hello.zr`)
* Has static typing, [UFCS](https://en.wikipedia.org/wiki/Uniform_function_call_syntax), variadics, dynamic arrays, hashmaps, DNS resolver, etc. * Has static typing, [UFCS](https://en.wikipedia.org/wiki/Uniform_function_call_syntax), generics, variadics, dynamic arrays, hashmaps, DNS resolver, etc.
## Syntax ## Syntax
```rust ```rust
include "$/io.zr"
func main[] : i64 func main[] : i64
answer := os.urandom_i64()->abs() % 100 answer := os.urandom_i64()->abs() % 100

View File

@@ -1,4 +1,4 @@
include "std/io.zr" include "$/io.zr"
func main[] : i64 func main[] : i64
// https://brainfuck.org/sierpinski.b // https://brainfuck.org/sierpinski.b

View File

@@ -1,6 +1,6 @@
// needs to be compiled with -m -C "-lraylib" // needs to be compiled with -m -C "-lraylib"
include "std/io.zr" include "$/io.zr"
include "std/os.zr" include "$/os.zr"
extern InitWindow extern InitWindow
extern SetTargetFPS extern SetTargetFPS
@@ -14,15 +14,15 @@ extern IsKeyDown
struct CHIP8 struct CHIP8
memory: ptr memory: ptr
pc: i64 pc: i64
stack: Array stack: Array<i64>
sp: i64 sp: i64
reg: ptr reg: ptr
I: i64 I: i64
delay_timer: u8 delay_timer: u8
sound_timer: u8 sound_timer: u8
keyboard: Array keyboard: Array<i64>
display: ptr display: ptr
keyboard_map: Array keyboard_map: Array<i64>
func CHIP8.init[c: CHIP8] : void func CHIP8.init[c: CHIP8] : void
c->memory = mem.alloc(4096) c->memory = mem.alloc(4096)
@@ -52,7 +52,7 @@ func CHIP8.free[c: CHIP8] : void
c->keyboard->free() c->keyboard->free()
c->display->free() c->display->free()
c->keyboard_map->free() c->keyboard_map->free()
mem.free(c) (c as ptr)->free()
func CHIP8.disassemble[c: CHIP8, ins_count: i64] : void func CHIP8.disassemble[c: CHIP8, ins_count: i64] : void
for i in 0..ins_count for i in 0..ins_count
@@ -201,7 +201,7 @@ func CHIP8.step[c: CHIP8] : void
else if n == 0x3 else if n == 0x3
c->reg[x] = c->reg[x] ^ c->reg[y] c->reg[x] = c->reg[x] ^ c->reg[y]
else if n == 0x4 else if n == 0x4
res : u8 = c->reg[x] + c->reg[y] res := c->reg[x] + c->reg[y]
c->reg[0xf] = (res > 0xff) as u8 c->reg[0xf] = (res > 0xff) as u8
c->reg[x] = res c->reg[x] = res
else if n == 0x5 else if n == 0x5
@@ -230,8 +230,8 @@ func CHIP8.step[c: CHIP8] : void
for row in 0..n for row in 0..n
for col in 0..8 for col in 0..8
if (c->memory[c->I + row] & (0x80 >> col)) != 0 if (c->memory[c->I + row] & (0x80 >> col)) != 0
pixel_x : u8 = (c->reg[x] + col) % 64 pixel_x := (c->reg[x] + col) % 64
pixel_y : u8 = (c->reg[y] + row) % 32 pixel_y := (c->reg[y] + row) % 32
offset := pixel_x as i64 + (pixel_y * 64) offset := pixel_x as i64 + (pixel_y * 64)
if c->display[offset] == 1 if c->display[offset] == 1
@@ -242,14 +242,14 @@ func CHIP8.step[c: CHIP8] : void
if IsKeyDown(c->keyboard_map->nth(c->reg[x] as i64)) if IsKeyDown(c->keyboard_map->nth(c->reg[x] as i64))
c->pc += 2 c->pc += 2
else if kk == 0xa1 else if kk == 0xa1
if !IsKeyDown(c->keyboard_map->nth(c->reg[x] as i64)) if !(IsKeyDown(c->keyboard_map->nth(c->reg[x] as i64)) as bool)
c->pc += 2 c->pc += 2
else if op == 0xf else if op == 0xf
if kk == 0x07 if kk == 0x07
c->reg[x] = c->delay_timer c->reg[x] = c->delay_timer
else if kk == 0x0A else if kk == 0x0A
key_pressed := false key_pressed := false
while !key_pressed && !WindowShouldClose() while !key_pressed && !(WindowShouldClose() as bool)
for i in 0..16 for i in 0..16
if IsKeyDown(c->keyboard_map->nth(i)) if IsKeyDown(c->keyboard_map->nth(i))
key_pressed = true key_pressed = true
@@ -278,7 +278,7 @@ func main[argc: i64, argv: ptr] : i64
disassemble := false disassemble := false
for i in 1..argc for i in 1..argc
arg := mem.read64(argv + i * 8) as str arg := os.arg(argv, i)
if arg->equal("-d") if arg->equal("-d")
disassemble = true disassemble = true
else else
@@ -291,7 +291,7 @@ func main[argc: i64, argv: ptr] : i64
c := new CHIP8 c := new CHIP8
c->init() c->init()
~buffer, ok := io.read_binary_file(path) buffer, ok := io.read_binary_file(path)
if !ok if !ok
panic("failed to read file") panic("failed to read file")
@@ -305,7 +305,7 @@ func main[argc: i64, argv: ptr] : i64
InitWindow(640, 320, "CHIP-8") InitWindow(640, 320, "CHIP-8")
SetTargetFPS(60) SetTargetFPS(60)
while !WindowShouldClose() while !(WindowShouldClose() as bool)
if c->delay_timer > 0 if c->delay_timer > 0
c->delay_timer = c->delay_timer - 1 c->delay_timer = c->delay_timer - 1
if c->sound_timer > 0 if c->sound_timer > 0

View File

@@ -1,18 +1,18 @@
include "std/io.zr" include "$/io.zr"
include "std/net.zr" include "$/net.zr"
func main[argc: i64, argv: ptr] : i64 func main[argc: i64, argv: ptr] : i64
if argc < 2 if argc < 2
io.println("ERROR: url is missing") io.println("ERROR: url is missing")
return 1 return 1
url := mem.read64(argv + 8) as str url := os.arg(argv, 1)
if url->len() <= 7 if url->len() <= 7
io.println("ERROR: invalid url (Did you forget \"http://\"?)") io.println("ERROR: invalid url (Did you forget \"http://\"?)")
return 1 return 1
if !url->substr(0, 7)->equal("http://") if !url->substr_n(0, 7)->equal("http://")
io.println("ERROR: only http scheme is supported") io.println("ERROR: only http scheme is supported")
return 1 return 1
@@ -24,23 +24,19 @@ func main[argc: i64, argv: ptr] : i64
break break
i += 1 i += 1
host := url->substr(host_start, i - host_start) host := url->substr_n(host_start, i - host_start)
path := "/" path := "/"
if i < url_len if i < url_len
path = url->substr(i, url_len - i) path = url->substr_n(i, url_len - i)
~s, ok := net.connect(host, 80) s, ok := net.connect(host, 80)
if !ok if !ok
panic("failed to connect") panic("failed to connect")
req := new str.Builder // seems reasonable
req->append("GET ") req := _stackalloc(4096) as str
req->append(path) req_size := req->format_into(4096, "GET %s HTTP/1.0\r\nHost: %s\r\nConnection: close\r\n\r\n", path, host)
req->append(" HTTP/1.0\r\nHost: ") net.send(s, req as ptr, req_size)
req->append(host)
req->append("\r\nConnection: close\r\n\r\n")
net.send(s, req->data, req->size)
req->destroy()
header_buf := mem.alloc(8192) as str header_buf := mem.alloc(8192) as str
header_size := 0 header_size := 0

View File

@@ -1,4 +1,4 @@
include "std/io.zr" include "$/io.zr"
func main[] : i64 func main[] : i64
sum := 0 sum := 0

View File

@@ -1,4 +1,4 @@
include "std/io.zr" include "$/io.zr"
func main[] : i64 func main[] : i64
sum := 0 sum := 0

View File

@@ -1,4 +1,4 @@
include "std/io.zr" include "$/io.zr"
func main[] : i64 func main[] : i64
sum := 0 sum := 0

View File

@@ -1,4 +1,4 @@
include "std/io.zr" include "$/io.zr"
func main[] : i64 func main[] : i64
n := 600851475143 n := 600851475143

View File

@@ -1,4 +1,4 @@
include "std/io.zr" include "$/io.zr"
func main[] : i64 func main[] : i64
out := 0 out := 0

View File

@@ -1,4 +1,4 @@
include "std/io.zr" include "$/io.zr"
func main[] : i64 func main[] : i64
out := 1 out := 1

View File

@@ -1,4 +1,4 @@
include "std/io.zr" include "$/io.zr"
func main[] : i64 func main[] : i64
sum_of_squares := 0 sum_of_squares := 0

View File

@@ -1,4 +1,4 @@
include "std/io.zr" include "$/io.zr"
func main[] : i64 func main[] : i64
found := 0 found := 0

View File

@@ -1,4 +1,4 @@
include "std/io.zr" include "$/io.zr"
func main[] : i64 func main[] : i64
n := "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450" n := "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450"

View File

@@ -1,4 +1,4 @@
include "std/io.zr" include "$/io.zr"
func main[] : i64 func main[] : i64
for a in 1..1000 for a in 1..1000

View File

@@ -1,4 +1,4 @@
include "std/io.zr" include "$/io.zr"
func main[] : i64 func main[] : i64
sum := 0 sum := 0

View File

@@ -1,10 +1,10 @@
include "std/io.zr" include "$/io.zr"
include "std/containers.zr" include "$/containers.zr"
func main[] : i64 func main[] : i64
N := 20 N := 20
grid := [] grid := [] as Array<Array<i64> >
grid->push([8, 2, 22, 97, 38, 15, 0, 40, 0, 75, 4, 5, 7, 78, 52, 12, 50, 77, 91, 8]) grid->push([8, 2, 22, 97, 38, 15, 0, 40, 0, 75, 4, 5, 7, 78, 52, 12, 50, 77, 91, 8])
grid->push([49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 4, 56, 62, 0]) grid->push([49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 4, 56, 62, 0])
grid->push([81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 3, 49, 13, 36, 65]) grid->push([81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 3, 49, 13, 36, 65])
@@ -30,10 +30,10 @@ func main[] : i64
for i in 0..N-3 for i in 0..N-3
for j in 0..N-3 for j in 0..N-3
h : i64 = (grid->nth(i) as Array)->nth(j) * (grid->nth(i) as Array)->nth(j+1) * (grid->nth(i) as Array)->nth(j+2) * (grid->nth(i) as Array)->nth(j+3) h := grid->nth(i)->nth(j) * grid->nth(i)->nth(j+1) * grid->nth(i)->nth(j+2) * grid->nth(i)->nth(j+3)
v : i64 = (grid->nth(j) as Array)->nth(i) * (grid->nth(j+1) as Array)->nth(i) * (grid->nth(j+2) as Array)->nth(i) * (grid->nth(j+3) as Array)->nth(i) v := grid->nth(j)->nth(i) * grid->nth(j+1)->nth(i) * grid->nth(j+2)->nth(i) * grid->nth(j+3)->nth(i)
d1 : i64 = (grid->nth(i) as Array)->nth(j) * (grid->nth(i+1) as Array)->nth(j+1) * (grid->nth(i+2) as Array)->nth(j+2) * (grid->nth(i+3) as Array)->nth(j+3) d1 := grid->nth(i)->nth(j) * grid->nth(i+1)->nth(j+1) * grid->nth(i+2)->nth(j+2) * grid->nth(i+3)->nth(j+3)
d2 : i64 = (grid->nth(i) as Array)->nth(N-j-1) * (grid->nth(i+1) as Array)->nth(N-j-2) * (grid->nth(i+2) as Array)->nth(N-j-3) * (grid->nth(i+3) as Array)->nth(N-j-4) d2 := grid->nth(i)->nth(N-j-1) * grid->nth(i+1)->nth(N-j-2) * grid->nth(i+2)->nth(N-j-3) * grid->nth(i+3)->nth(N-j-4)
out = math.max(out, math.max(h, math.max(v, math.max(d1, d2)))) out = math.max(out, math.max(h, math.max(v, math.max(d1, d2))))
io.println_i64(out) io.println_i64(out)

View File

@@ -1,4 +1,4 @@
include "std/io.zr" include "$/io.zr"
func num_divisors[n: i64] : i64 func num_divisors[n: i64] : i64
end := n->isqrt() end := n->isqrt()

View File

@@ -1,5 +1,5 @@
include "std/io.zr" include "$/io.zr"
func main[] : i64 func main[] : i64
n := 37107287533 + 46376937677 + 74324986199 + 91942213363 + 23067588207 + 89261670696 + 28112879812 + 44274228917 + 47451445736 + 70386486105 + 62176457141 + 64906352462 + 92575867718 + 58203565325 + 80181199384 + 35398664372 + 86515506006 + 71693888707 + 54370070576 + 53282654108 + 36123272525 + 45876576172 + 17423706905 + 81142660418 + 51934325451 + 62467221648 + 15732444386 + 55037687525 + 18336384825 + 80386287592 + 78182833757 + 16726320100 + 48403098129 + 87086987551 + 59959406895 + 69793950679 + 41052684708 + 65378607361 + 35829035317 + 94953759765 + 88902802571 + 25267680276 + 36270218540 + 24074486908 + 91430288197 + 34413065578 + 23053081172 + 11487696932 + 63783299490 + 67720186971 + 95548255300 + 76085327132 + 37774242535 + 23701913275 + 29798860272 + 18495701454 + 38298203783 + 34829543829 + 40957953066 + 29746152185 + 41698116222 + 62467957194 + 23189706772 + 86188088225 + 11306739708 + 82959174767 + 97623331044 + 42846280183 + 55121603546 + 32238195734 + 75506164965 + 62177842752 + 32924185707 + 99518671430 + 73267460800 + 76841822524 + 97142617910 + 87783646182 + 10848802521 + 71329612474 + 62184073572 + 66627891981 + 60661826293 + 85786944089 + 66024396409 + 64913982680 + 16730939319 + 94809377245 + 78639167021 + 15368713711 + 40789923115 + 44889911501 + 41503128880 + 81234880673 + 82616570773 + 22918802058 + 77158542502 + 72107838435 + 20849603980 + 53503534226 n := 37107287533 + 46376937677 + 74324986199 + 91942213363 + 23067588207 + 89261670696 + 28112879812 + 44274228917 + 47451445736 + 70386486105 + 62176457141 + 64906352462 + 92575867718 + 58203565325 + 80181199384 + 35398664372 + 86515506006 + 71693888707 + 54370070576 + 53282654108 + 36123272525 + 45876576172 + 17423706905 + 81142660418 + 51934325451 + 62467221648 + 15732444386 + 55037687525 + 18336384825 + 80386287592 + 78182833757 + 16726320100 + 48403098129 + 87086987551 + 59959406895 + 69793950679 + 41052684708 + 65378607361 + 35829035317 + 94953759765 + 88902802571 + 25267680276 + 36270218540 + 24074486908 + 91430288197 + 34413065578 + 23053081172 + 11487696932 + 63783299490 + 67720186971 + 95548255300 + 76085327132 + 37774242535 + 23701913275 + 29798860272 + 18495701454 + 38298203783 + 34829543829 + 40957953066 + 29746152185 + 41698116222 + 62467957194 + 23189706772 + 86188088225 + 11306739708 + 82959174767 + 97623331044 + 42846280183 + 55121603546 + 32238195734 + 75506164965 + 62177842752 + 32924185707 + 99518671430 + 73267460800 + 76841822524 + 97142617910 + 87783646182 + 10848802521 + 71329612474 + 62184073572 + 66627891981 + 60661826293 + 85786944089 + 66024396409 + 64913982680 + 16730939319 + 94809377245 + 78639167021 + 15368713711 + 40789923115 + 44889911501 + 41503128880 + 81234880673 + 82616570773 + 22918802058 + 77158542502 + 72107838435 + 20849603980 + 53503534226
io.println(n->to_str()->substr(0, 10)) io.println(n->to_str()->substr_n(0, 10))

View File

@@ -1,4 +1,4 @@
include "std/io.zr" include "$/io.zr"
func collatz_num[n: i64] : i64 func collatz_num[n: i64] : i64
if n % 2 == 0 if n % 2 == 0

View File

@@ -1,4 +1,4 @@
include "std/io.zr" include "$/io.zr"
func main[] : i64 func main[] : i64
n := 40 n := 40

View File

@@ -1,5 +1,5 @@
include "std/io.zr" include "$/io.zr"
include "std/containers.zr" include "$/containers.zr"
func main[] : i64 func main[] : i64
n := [1] n := [1]
@@ -7,7 +7,7 @@ func main[] : i64
for j in 0..1000 for j in 0..1000
carry := 0 carry := 0
for i in 0..n->size for i in 0..n->size
tmp : i64 = n->nth(i) * 2 + carry tmp := n->nth(i) * 2 + carry
n->set(i, tmp % 10) n->set(i, tmp % 10)
carry = tmp / 10 carry = tmp / 10
while carry > 0 while carry > 0

View File

@@ -1,5 +1,5 @@
include "std/io.zr" include "$/io.zr"
include "std/containers.zr" include "$/containers.zr"
func main[] : i64 func main[] : i64
s1 := [0, 3, 3, 5, 4, 4, 3, 5, 5, 4] s1 := [0, 3, 3, 5, 4, 4, 3, 5, 5, 4]

View File

@@ -1,17 +1,17 @@
include "std/io.zr" include "$/io.zr"
include "std/containers.zr" include "$/containers.zr"
func findmax[triangle: Array, row: i64, col: i64] : i64 func findmax[triangle: Array<Array<i64> >, row: i64, col: i64] : i64
if row == 14 if row == 14
return (triangle->nth(row) as Array)->nth(col) return triangle->nth(row)->nth(col)
left := findmax(triangle, row + 1, col) left := findmax(triangle, row + 1, col)
right := findmax(triangle, row + 1, col + 1) right := findmax(triangle, row + 1, col + 1)
return (triangle->nth(row) as Array)->nth(col) + math.max(left, right) return triangle->nth(row)->nth(col) + math.max(left, right)
func main[] : i64 func main[] : i64
triangle := [] triangle := [] as Array<Array<i64> >
triangle->push([75]) triangle->push([75])
triangle->push([95, 64]) triangle->push([95, 64])
triangle->push([17, 47, 82]) triangle->push([17, 47, 82])

View File

@@ -1,4 +1,4 @@
include "std/io.zr" include "$/io.zr"
func days[y: i64, m: i64] : i64 func days[y: i64, m: i64] : i64
if m == 2 if m == 2

View File

@@ -1,10 +1,10 @@
include "std/io.zr" include "$/io.zr"
include "std/containers.zr" include "$/containers.zr"
func multiply[n: Array, x: i64] : void func multiply[n: Array<i64>, x: i64] : void
carry := 0 carry := 0
for i in 0..n->size for i in 0..n->size
prod : i64 = n->nth(i) * x + carry prod := n->nth(i) * x + carry
n->set(i, prod % 10) n->set(i, prod % 10)
carry = prod / 10 carry = prod / 10
while carry > 0 while carry > 0

View File

@@ -1,4 +1,4 @@
include "std/io.zr" include "$/io.zr"
func divisors_sum[n: i64] : i64 func divisors_sum[n: i64] : i64
k := n k := n

View File

@@ -1,4 +1,4 @@
include "std/io.zr" include "$/io.zr"
func main[] : i64 func main[] : i64
a := 0 a := 0

View File

@@ -1,4 +1,4 @@
include "std/io.zr" include "$/io.zr"
func main[] : i64 func main[] : i64
for i in 1..40 for i in 1..40

View File

@@ -1,5 +1,5 @@
include "std/io.zr" include "$/io.zr"
include "std/os.zr" include "$/os.zr"
func main[] : i64 func main[] : i64
answer := os.urandom_i64()->abs() % 100 answer := os.urandom_i64()->abs() % 100

View File

@@ -1,4 +0,0 @@
include "std/io.zr"
func main[] : i64
io.println("Hello, World!")

View File

@@ -1,18 +0,0 @@
include "std/io.zr"
include "std/os.zr"
func main[] : i64
arr := []
for i in 0..10
arr->push(os.urandom_i64()->abs() % 1000)
for i in 0..arr->size
io.println_i64(arr->nth(i))
io.println("------------")
arr->quicksort()
for i in 0..arr->size
io.println_i64(arr->nth(i))
arr->free()

View File

@@ -1,5 +1,5 @@
// needs to be compiled with -m -C "-lraylib" // needs to be compiled with -m -C "-lraylib"
include "std/io.zr" include "$/io.zr"
extern InitWindow extern InitWindow
extern SetTargetFPS extern SetTargetFPS
@@ -26,14 +26,14 @@ func main[] : i64
InitWindow(800, 600, "Hello, World!") InitWindow(800, 600, "Hello, World!")
SetTargetFPS(60) SetTargetFPS(60)
while !WindowShouldClose() while !(WindowShouldClose() as bool)
if IsKeyDown(KEY_W) & 255 if IsKeyDown(KEY_W) as u8 & 255
y -= 10 y -= 10
if IsKeyDown(KEY_S) & 255 if IsKeyDown(KEY_S) as u8 & 255
y += 10 y += 10
if IsKeyDown(KEY_A) & 255 if IsKeyDown(KEY_A) as u8 & 255
x -= 10 x -= 10
if IsKeyDown(KEY_D) & 255 if IsKeyDown(KEY_D) as u8 & 255
x += 10 x += 10
BeginDrawing() BeginDrawing()

View File

@@ -1,14 +1,14 @@
include "std/io.zr" include "$/io.zr"
include "std/containers.zr" include "$/containers.zr"
func rule110_step[state: Array] : void func rule110_step[state: Array<bool>] : void
new_state := [] new_state := [] as Array<bool>
for i in 0..state->size for i in 0..state->size
left := false left := false
if i - 1 >= 0 if i - 1 >= 0
left = state->nth(i - 1) left = state->nth(i - 1)
center : bool = state->nth(i) center := state->nth(i)
right := false right := false
if i + 1 < state->size if i + 1 < state->size
right = state->nth(i + 1) right = state->nth(i + 1)
@@ -18,7 +18,7 @@ func rule110_step[state: Array] : void
mem.copy(new_state->data, state->data, state->size * 8) mem.copy(new_state->data, state->data, state->size * 8)
new_state->free() new_state->free()
func print_state[state: Array]: void func print_state[state: Array<bool>]: void
for i in 0..state->size for i in 0..state->size
if state->nth(i) if state->nth(i)
io.print_char('#') io.print_char('#')
@@ -29,7 +29,7 @@ func print_state[state: Array]: void
func main[] : i64 func main[] : i64
SIZE := 60 SIZE := 60
state := [] state := [] as Array<bool>
for i in 0..SIZE for i in 0..SIZE
state->push(false) state->push(false)
state->push(true) state->push(true)

96
examples/serve.zr Normal file
View File

@@ -0,0 +1,96 @@
// needs to be compiled with -m -C "-lpthread"
include "$/net.zr"
extern pthread_create
extern pthread_detach
struct ConnData
sock: i64
addr: str
func handle_connection[conn: ConnData] : void
req := _stackalloc(10001) as str
n := net.read(conn->sock, req as ptr, 10000)
if n <= 0
net.close(conn->sock)
conn->addr->free()
(conn as ptr)->free()
return
req[n] = 0
pos := req->find("\r\n")
if pos == -1
panic("TODO: bad request")
first_line := req->substr_n(0, pos)
parts := first_line->split(" ")
method := parts->nth(0) as str
path := parts->nth(1) as str
if !method->equal("GET")
// TODO: method not supported
return
if path->equal("/")
// TODO: index
return
// TODO: ANY validation
file_path := "."->concat(path)
file_size, ok := os.get_file_size(file_path)
if !ok
// TODO: not found
return
fd := _builtin_syscall(SYS_openat, AT_FDCWD, file_path, O_RDONLY, 0)
if fd < 0
// TODO: not found
return
resp := "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n"
net.send(conn->sock, resp as ptr, resp->len())
offset := 0
while offset < file_size
sent := _builtin_syscall(SYS_sendfile, conn->sock, fd, ^offset, IP_MAXPACKET)
if sent <= 0
break
net.close(conn->sock)
_builtin_syscall(SYS_close, fd)
file_path->free()
first_line->free()
parts->free_with_items()
conn->addr->free()
(conn as ptr)->free()
func main[argc: i64, argv: ptr] : i64
port := 8000
if argc > 1
port = os.arg(argv, 1)->parse_i64()
server_sock, ok := net.listen("0.0.0.0", port)
if !ok
panic("failed to listen")
io.printf("Listening on :%d...\n", port)
addr := _stackalloc(16)
while true
conn := net.accept(server_sock, addr)
if conn < 0
io.println("ERROR: failed to accept connection")
continue
conn_data := new* ConnData
conn_data->sock = conn
conn_data->addr = mem.alloc(30) as str
conn_data->addr->format_into(30, "%d.%d.%d.%d:%d", addr[4], addr[5], addr[6], addr[7], mem.read16be(addr + 2))
thread := 0
pthread_create(^thread, 0, ^handle_connection, conn_data)
pthread_detach(thread)

View File

@@ -1,5 +1,5 @@
// needs to be compiled with -m -C "-lsqlite3" // needs to be compiled with -m -C "-lsqlite3"
include "std/io.zr" include "$/io.zr"
extern sqlite3_open extern sqlite3_open
extern sqlite3_exec extern sqlite3_exec
@@ -20,13 +20,13 @@ func main[] : i64
db := 0 db := 0
stmt := 0 stmt := 0
rc = sqlite3_open("todo.db", ^db) rc = sqlite3_open("todo.db", ^db) as i64
if rc if rc
panic("failed to open db") panic("failed to open db")
rc = sqlite3_exec(db, "CREATE TABLE IF NOT EXISTS todo(id INTEGER PRIMARY KEY AUTOINCREMENT, task TEXT NOT NULL);", 0, 0, 0) rc = sqlite3_exec(db, "CREATE TABLE IF NOT EXISTS todo(id INTEGER PRIMARY KEY AUTOINCREMENT, task TEXT NOT NULL);", 0, 0, 0) as i64
if rc if rc
panic(sqlite3_errmsg(db)) panic(sqlite3_errmsg(db) as str)
while true while true
io.println("1. List tasks") io.println("1. List tasks")
@@ -43,7 +43,7 @@ func main[] : i64
io.println("============") io.println("============")
sqlite3_prepare_v2(db, "SELECT * FROM todo", -1, ^stmt, 0) sqlite3_prepare_v2(db, "SELECT * FROM todo", -1, ^stmt, 0)
while sqlite3_step(stmt) == SQLITE_ROW while sqlite3_step(stmt) as i64 == SQLITE_ROW
id := sqlite3_column_int(stmt, 0) as i64 id := sqlite3_column_int(stmt, 0) as i64
task := sqlite3_column_text(stmt, 1) as str task := sqlite3_column_text(stmt, 1) as str
io.printf("%d - %s\n", id, task) io.printf("%d - %s\n", id, task)
@@ -55,8 +55,8 @@ func main[] : i64
sqlite3_prepare_v2(db, "INSERT INTO todo(task) VALUES (?);", -1, ^stmt, 0) sqlite3_prepare_v2(db, "INSERT INTO todo(task) VALUES (?);", -1, ^stmt, 0)
sqlite3_bind_text(stmt, 1, task, -1, 0) sqlite3_bind_text(stmt, 1, task, -1, 0)
if sqlite3_step(stmt) != SQLITE_DONE if sqlite3_step(stmt) as i64 != SQLITE_DONE
panic(sqlite3_errmsg(db)) panic(sqlite3_errmsg(db) as str)
io.println("\nTask added\n") io.println("\nTask added\n")
else if choice == 3 else if choice == 3
@@ -65,8 +65,8 @@ func main[] : i64
sqlite3_prepare_v2(db, "DELETE FROM todo WHERE id = ?;", -1, ^stmt, 0) sqlite3_prepare_v2(db, "DELETE FROM todo WHERE id = ?;", -1, ^stmt, 0)
sqlite3_bind_int(stmt, 1, id, -1, 0) sqlite3_bind_int(stmt, 1, id, -1, 0)
if sqlite3_step(stmt) != SQLITE_DONE if sqlite3_step(stmt) as i64 != SQLITE_DONE
panic(sqlite3_errmsg(db)) panic(sqlite3_errmsg(db) as str)
io.println("\nTask deleted\n") io.println("\nTask deleted\n")

View File

@@ -1,26 +0,0 @@
include "std/io.zr"
include "std/net.zr"
func main[] : i64
~s, ok := net.listen("127.0.0.1", 8000)
if !ok
panic("failed to listen")
io.println("Listening on port 8000...")
resp := mem.alloc(IP_MAXPACKET)
addr := _stackalloc(16)
while true
conn := net.accept(s, addr)
if conn < 0
continue
io.printf("%d.%d.%d.%d:%d\n", addr[4], addr[5], addr[6], addr[7], mem.read16be(addr + 2))
n := net.read(conn, resp, IP_MAXPACKET)
io.print_sized(resp, n)
io.println("")
net.send(conn, resp, n)
net.close(conn)

View File

@@ -1,8 +1,8 @@
include "std/io.zr" include "$/io.zr"
include "std/net.zr" include "$/net.zr"
func main[] : i64 func main[] : i64
~s, ok := net.create_udp_server("127.0.0.1", 8000) s, ok := net.create_udp_server("127.0.0.1", 8000)
if !ok if !ok
panic("net.create_udp_server failed") panic("net.create_udp_server failed")

View File

@@ -215,11 +215,7 @@ _builtin_environ:
pub fn compile_stmt(&mut self, env: &mut Env, stmt: &Stmt) -> Result<(), ZernError> { pub fn compile_stmt(&mut self, env: &mut Env, stmt: &Stmt) -> Result<(), ZernError> {
match stmt { match stmt {
Stmt::Expression(expr) => self.compile_expr(env, expr)?, Stmt::Expression(expr) => self.compile_expr(env, expr)?,
Stmt::Declare { Stmt::Declare { name, initializer } => {
name,
var_type,
initializer,
} => {
// TODO: move to typechecker? // TODO: move to typechecker?
if env.get_var(&name.lexeme).is_some() { if env.get_var(&name.lexeme).is_some() {
return error!( return error!(
@@ -228,12 +224,9 @@ _builtin_environ:
); );
} }
let var_type: String = match var_type { let var_type: String = match self.expr_types[&initializer.id].as_str() {
Some(t) => t.lexeme.clone(), "opaque" => return error!(name.loc, "cannot infer type from opaque"),
None => match self.expr_types[&initializer.id].as_str() {
"any" => return error!(name.loc, "cannot infer type from any"),
t => t.into(), t => t.into(),
},
}; };
self.compile_expr(env, initializer)?; self.compile_expr(env, initializer)?;
@@ -660,13 +653,8 @@ _builtin_environ:
self.compile_expr(env, right)?; self.compile_expr(env, right)?;
match op.token_type { match op.token_type {
TokenType::Minus => { TokenType::Minus => {
if self.expr_types[&right.id] == "f64" {
emit!(&mut self.output, " mov rbx, 0x8000000000000000");
emit!(&mut self.output, " xor rax, rbx");
} else {
emit!(&mut self.output, " neg rax"); emit!(&mut self.output, " neg rax");
} }
}
TokenType::Bang => { TokenType::Bang => {
emit!(&mut self.output, " test rax, rax"); emit!(&mut self.output, " test rax, rax");
emit!(&mut self.output, " sete al"); emit!(&mut self.output, " sete al");
@@ -806,13 +794,13 @@ _builtin_environ:
struct_name, struct_name,
use_heap, use_heap,
} => { } => {
let struct_fields = &self.symbol_table.structs[&struct_name.lexeme]; let struct_fields =
&self.symbol_table.structs[self.strip_generic(&struct_name.lexeme)];
let memory_size = struct_fields.len() * 8; let memory_size = struct_fields.len() * 8;
if *use_heap { if *use_heap {
emit!(&mut self.output, " mov rdi, {}", memory_size); emit!(&mut self.output, " mov rdi, {}", memory_size);
emit!(&mut self.output, " call mem.alloc"); emit!(&mut self.output, " call mem.alloc");
emit!(&mut self.output, " push rax");
} else { } else {
let aligned_size = (memory_size + 15) & !15; let aligned_size = (memory_size + 15) & !15;
emit!(&mut self.output, " sub rsp, {}", aligned_size); emit!(&mut self.output, " sub rsp, {}", aligned_size);
@@ -836,7 +824,8 @@ _builtin_environ:
} }
ExprKind::MethodCall { expr, method, args } => { ExprKind::MethodCall { expr, method, args } => {
let receiver_type = &self.expr_types[&expr.id]; let receiver_type = &self.expr_types[&expr.id];
let func_name = format!("{}.{}", receiver_type, method.lexeme); let base_type = self.strip_generic(receiver_type);
let func_name = format!("{}.{}", base_type, method.lexeme);
self.compile_expr(env, expr)?; self.compile_expr(env, expr)?;
emit!(&mut self.output, " push rax"); emit!(&mut self.output, " push rax");
@@ -911,8 +900,12 @@ _builtin_environ:
} }
} }
fn strip_generic<'b>(&self, type_name: &'b str) -> &'b str {
type_name.split('<').next().unwrap_or(type_name)
}
fn get_field_offset(&self, left: &Expr, field: &Token) -> Result<usize, ZernError> { fn get_field_offset(&self, left: &Expr, field: &Token) -> Result<usize, ZernError> {
let struct_name = &self.expr_types[&left.id]; let struct_name = self.strip_generic(&self.expr_types[&left.id]);
let fields = match self.symbol_table.structs.get(struct_name) { let fields = match self.symbol_table.structs.get(struct_name) {
Some(f) => f, Some(f) => f,

View File

@@ -7,16 +7,11 @@ mod typechecker;
use std::{ use std::{
collections::HashSet, collections::HashSet,
fs, fs,
path::Path,
process::{self, Command}, process::{self, Command},
}; };
use tokenizer::ZernError; use tokenizer::ZernError;
#[cfg(feature = "mimalloc")]
#[global_allocator]
static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;
fn compile_file(args: Args) -> Result<(), ZernError> { fn compile_file(args: Args) -> Result<(), ZernError> {
let source = match fs::read_to_string(&args.path) { let source = match fs::read_to_string(&args.path) {
Ok(x) => x, Ok(x) => x,
@@ -26,10 +21,8 @@ fn compile_file(args: Args) -> Result<(), ZernError> {
} }
}; };
let filename = Path::new(&args.path).file_name().unwrap().to_str().unwrap();
let mut included_paths = HashSet::new(); let mut included_paths = HashSet::new();
let tokenizer = tokenizer::Tokenizer::new(filename.to_owned(), source, &mut included_paths); let tokenizer = tokenizer::Tokenizer::new(args.path, source, &mut included_paths);
let parser = parser::Parser::new(tokenizer.tokenize()?); let parser = parser::Parser::new(tokenizer.tokenize()?);
let statements = parser.parse()?; let statements = parser.parse()?;

View File

@@ -1,7 +1,7 @@
use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::atomic::{AtomicUsize, Ordering};
use crate::tokenizer::{ use crate::tokenizer::{
Token, Loc, Token,
TokenType::{self, Identifier}, TokenType::{self, Identifier},
ZernError, error, ZernError, error,
}; };
@@ -23,7 +23,6 @@ pub enum Stmt {
Expression(Expr), Expression(Expr),
Declare { Declare {
name: Token, name: Token,
var_type: Option<Token>,
initializer: Expr, initializer: Expr,
}, },
Assign { Assign {
@@ -79,6 +78,40 @@ pub enum Stmt {
}, },
} }
// https://stackoverflow.com/a/29963675
pub struct ScopeCall<F: FnMut()> {
pub c: F,
}
impl<F: FnMut()> Drop for ScopeCall<F> {
fn drop(&mut self) {
(self.c)();
}
}
macro_rules! recursion_guard {
($self:ident) => {
$self.depth += 1;
if $self.depth > 200 {
return error!(
Loc {
filename: "<unknown>".into(),
line: 0,
column: 0,
},
"maximum expression depth reached"
);
}
let self_ptr = $self as *mut Self;
let _scope_call = ScopeCall {
c: || unsafe {
(*self_ptr).depth -= 1;
},
};
};
}
pub(crate) use recursion_guard;
pub static NEXT_EXPR_ID: AtomicUsize = AtomicUsize::new(0); pub static NEXT_EXPR_ID: AtomicUsize = AtomicUsize::new(0);
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
@@ -175,6 +208,38 @@ impl Parser {
Ok(statements) Ok(statements)
} }
fn parse_type_ref(&mut self) -> Result<Token, ZernError> {
if self.match_token(&[TokenType::Dollar]) {
Ok(Token {
token_type: TokenType::Identifier,
lexeme: "$".to_string(),
loc: self.previous().loc.clone(),
})
} else {
let ident = self.consume(TokenType::Identifier, "expected type name")?;
let mut type_name = ident.lexeme.clone();
if self.match_token(&[TokenType::Less]) {
type_name.push('<');
loop {
let inner = self.parse_type_ref()?;
type_name.push_str(&inner.lexeme);
if self.match_token(&[TokenType::Comma]) {
type_name.push(',');
} else {
break;
}
}
self.consume(TokenType::Greater, "expected '>'")?;
type_name.push('>');
}
Ok(Token {
token_type: TokenType::Identifier,
lexeme: type_name,
loc: ident.loc,
})
}
}
fn declaration(&mut self) -> Result<Stmt, ZernError> { fn declaration(&mut self) -> Result<Stmt, ZernError> {
if !self.is_inside_function { if !self.is_inside_function {
if self.match_token(&[TokenType::KeywordFunc]) { if self.match_token(&[TokenType::KeywordFunc]) {
@@ -217,8 +282,7 @@ impl Parser {
self.consume(TokenType::Identifier, "expected parameter name")?; self.consume(TokenType::Identifier, "expected parameter name")?;
self.consume(TokenType::Colon, "expected ':' after parameter name")?; self.consume(TokenType::Colon, "expected ':' after parameter name")?;
let var_type = let var_type = self.parse_type_ref()?;
self.consume(TokenType::Identifier, "expected parameter type")?;
params.push(Param { var_type, var_name }); params.push(Param { var_type, var_name });
if !self.match_token(&[TokenType::Comma]) { if !self.match_token(&[TokenType::Comma]) {
@@ -233,7 +297,7 @@ impl Parser {
let mut return_types = vec![]; let mut return_types = vec![];
loop { loop {
return_types.push(self.consume(TokenType::Identifier, "expected return type")?); return_types.push(self.parse_type_ref()?);
if !self.match_token(&[TokenType::Comma]) { if !self.match_token(&[TokenType::Comma]) {
break; break;
} }
@@ -266,7 +330,7 @@ impl Parser {
let var_name = self.consume(TokenType::Identifier, "expected field name")?; let var_name = self.consume(TokenType::Identifier, "expected field name")?;
self.consume(TokenType::Colon, "expected ':' after field name")?; self.consume(TokenType::Colon, "expected ':' after field name")?;
let var_type = self.consume(TokenType::Identifier, "expected field type")?; let var_type = self.parse_type_ref()?;
fields.push(Param { var_type, var_name }); fields.push(Param { var_type, var_name });
} }
@@ -306,20 +370,10 @@ impl Parser {
let name = self.consume(TokenType::Identifier, "expected variable name")?; let name = self.consume(TokenType::Identifier, "expected variable name")?;
self.consume(TokenType::Colon, "expected ':'")?; self.consume(TokenType::Colon, "expected ':'")?;
let var_type = if self.match_token(&[TokenType::Equal]) { self.consume(TokenType::Equal, "expected '=' after ':'")?;
None
} else {
let var_type = self.consume(TokenType::Identifier, "expected variable type")?;
self.consume(TokenType::Equal, "expected '=' after varaible type")?;
Some(var_type)
};
let initializer = self.expression()?; let initializer = self.expression()?;
Ok(Stmt::Declare { Ok(Stmt::Declare { name, initializer })
name,
var_type,
initializer,
})
} else if self.match_token(&[TokenType::KeywordIf]) { } else if self.match_token(&[TokenType::KeywordIf]) {
self.if_statement() self.if_statement()
} else if self.match_token(&[TokenType::KeywordWhile]) { } else if self.match_token(&[TokenType::KeywordWhile]) {
@@ -342,7 +396,7 @@ impl Parser {
Ok(Stmt::Break) Ok(Stmt::Break)
} else if self.match_token(&[TokenType::KeywordContinue]) { } else if self.match_token(&[TokenType::KeywordContinue]) {
Ok(Stmt::Continue) Ok(Stmt::Continue)
} else if self.match_token(&[TokenType::Tilde]) { } else if self.check(&TokenType::Identifier) && self.check_ahead(&TokenType::Comma) {
let mut targets = vec![]; let mut targets = vec![];
loop { loop {
targets.push(self.consume(Identifier, "expected an identifier")?); targets.push(self.consume(Identifier, "expected an identifier")?);
@@ -448,17 +502,12 @@ impl Parser {
} }
fn expression(&mut self) -> Result<Expr, ZernError> { fn expression(&mut self) -> Result<Expr, ZernError> {
self.depth += 1; recursion_guard!(self);
if self.depth > 200 { self.or_and()
return error!(self.previous().loc, "maximum expression depth reached");
}
let out = self.or_and();
self.depth -= 1;
out
} }
fn or_and(&mut self) -> Result<Expr, ZernError> { fn or_and(&mut self) -> Result<Expr, ZernError> {
recursion_guard!(self);
let mut expr = self.equality()?; let mut expr = self.equality()?;
while self.match_token(&[TokenType::LogicalOr, TokenType::LogicalAnd]) { while self.match_token(&[TokenType::LogicalOr, TokenType::LogicalAnd]) {
@@ -475,6 +524,7 @@ impl Parser {
} }
fn equality(&mut self) -> Result<Expr, ZernError> { fn equality(&mut self) -> Result<Expr, ZernError> {
recursion_guard!(self);
let mut expr = self.comparison()?; let mut expr = self.comparison()?;
while self.match_token(&[TokenType::DoubleEqual, TokenType::NotEqual]) { while self.match_token(&[TokenType::DoubleEqual, TokenType::NotEqual]) {
@@ -491,6 +541,7 @@ impl Parser {
} }
fn comparison(&mut self) -> Result<Expr, ZernError> { fn comparison(&mut self) -> Result<Expr, ZernError> {
recursion_guard!(self);
let mut expr = self.term()?; let mut expr = self.term()?;
while self.match_token(&[ while self.match_token(&[
@@ -512,6 +563,7 @@ impl Parser {
} }
fn term(&mut self) -> Result<Expr, ZernError> { fn term(&mut self) -> Result<Expr, ZernError> {
recursion_guard!(self);
let mut expr = self.factor()?; let mut expr = self.factor()?;
while self.match_token(&[ while self.match_token(&[
@@ -534,6 +586,7 @@ impl Parser {
} }
fn factor(&mut self) -> Result<Expr, ZernError> { fn factor(&mut self) -> Result<Expr, ZernError> {
recursion_guard!(self);
let mut expr = self.cast()?; let mut expr = self.cast()?;
while self.match_token(&[ while self.match_token(&[
@@ -556,10 +609,11 @@ impl Parser {
} }
fn cast(&mut self) -> Result<Expr, ZernError> { fn cast(&mut self) -> Result<Expr, ZernError> {
recursion_guard!(self);
let mut expr = self.unary()?; let mut expr = self.unary()?;
while self.match_token(&[TokenType::KeywordAs]) { while self.match_token(&[TokenType::KeywordAs]) {
let type_name = self.consume(TokenType::Identifier, "expected type after 'as'")?; let type_name = self.parse_type_ref()?;
expr = Expr::new(ExprKind::Cast { expr = Expr::new(ExprKind::Cast {
expr: Box::new(expr), expr: Box::new(expr),
type_name, type_name,
@@ -570,6 +624,8 @@ impl Parser {
} }
fn unary(&mut self) -> Result<Expr, ZernError> { fn unary(&mut self) -> Result<Expr, ZernError> {
recursion_guard!(self);
if self.match_token(&[TokenType::Xor]) { if self.match_token(&[TokenType::Xor]) {
let op = self.previous().clone(); let op = self.previous().clone();
let right = self.unary()?; let right = self.unary()?;
@@ -591,6 +647,7 @@ impl Parser {
} }
fn call(&mut self) -> Result<Expr, ZernError> { fn call(&mut self) -> Result<Expr, ZernError> {
recursion_guard!(self);
let mut expr = self.primary()?; let mut expr = self.primary()?;
loop { loop {
@@ -688,8 +745,7 @@ impl Parser {
Ok(Expr::new(ExprKind::ArrayLiteral(xs))) Ok(Expr::new(ExprKind::ArrayLiteral(xs)))
} else if self.match_token(&[TokenType::KeywordNew]) { } else if self.match_token(&[TokenType::KeywordNew]) {
let use_heap = self.match_token(&[TokenType::Star]); let use_heap = self.match_token(&[TokenType::Star]);
let struct_name = let struct_name = self.parse_type_ref()?;
self.consume(TokenType::Identifier, "expected struct name after 'new'")?;
Ok(Expr::new(ExprKind::New { Ok(Expr::new(ExprKind::New {
struct_name, struct_name,
use_heap, use_heap,

View File

@@ -59,11 +59,11 @@ impl SymbolTable {
("_builtin_cvttsd2si".into(), FnType::new("i64", vec!["f64"])), ("_builtin_cvttsd2si".into(), FnType::new("i64", vec!["f64"])),
( (
"_builtin_f64_to_f32".into(), "_builtin_f64_to_f32".into(),
FnType::new("any", vec!["f64"]), FnType::new("opaque", vec!["f64"]),
), ),
("_builtin_syscall".into(), FnType::new_variadic("i64")), ("_builtin_syscall".into(), FnType::new_variadic("i64")),
("_builtin_environ".into(), FnType::new("ptr", vec![])), ("_builtin_environ".into(), FnType::new("ptr", vec![])),
("_var_arg".into(), FnType::new("any", vec!["i64"])), ("_var_arg".into(), FnType::new("opaque", vec!["i64"])),
("_stackalloc".into(), FnType::new("ptr", vec!["i64"])), ("_stackalloc".into(), FnType::new("ptr", vec!["i64"])),
]), ]),
constants: HashMap::new(), constants: HashMap::new(),
@@ -98,7 +98,7 @@ impl SymbolTable {
return error!(name.loc, format!("tried to redefine '{}'", name.lexeme)); return error!(name.loc, format!("tried to redefine '{}'", name.lexeme));
} }
self.functions self.functions
.insert(name.lexeme.clone(), FnType::new_variadic("any")); .insert(name.lexeme.clone(), FnType::new_variadic("opaque"));
} }
Stmt::Function { Stmt::Function {
name, name,

View File

@@ -30,7 +30,6 @@ pub enum TokenType {
ShiftLeft, ShiftLeft,
ShiftRight, ShiftRight,
Arrow, Arrow,
Tilde,
Equal, Equal,
DoubleEqual, DoubleEqual,
@@ -66,6 +65,7 @@ pub enum TokenType {
Indent, Indent,
Dedent, Dedent,
Dollar,
Eof, Eof,
} }
@@ -179,7 +179,6 @@ impl<'a> Tokenizer<'a> {
'%' => self.add_token(TokenType::Mod)?, '%' => self.add_token(TokenType::Mod)?,
'^' => self.add_token(TokenType::Xor)?, '^' => self.add_token(TokenType::Xor)?,
':' => self.add_token(TokenType::Colon)?, ':' => self.add_token(TokenType::Colon)?,
'~' => self.add_token(TokenType::Tilde)?,
'-' => { '-' => {
if self.match_char('=') { if self.match_char('=') {
self.add_token(TokenType::MinusEqual)? self.add_token(TokenType::MinusEqual)?
@@ -251,6 +250,7 @@ impl<'a> Tokenizer<'a> {
self.add_token(TokenType::Less)? self.add_token(TokenType::Less)?
} }
} }
'$' => self.add_token(TokenType::Dollar)?,
'\'' => { '\'' => {
if self.eof() { if self.eof() {
return error!(self.loc, "unterminated char literal"); return error!(self.loc, "unterminated char literal");
@@ -451,28 +451,53 @@ impl<'a> Tokenizer<'a> {
self.include_file(path) self.include_file(path)
} }
fn include_file(&mut self, path: String) -> Result<(), ZernError> { fn include_file(&mut self, mut path: String) -> Result<(), ZernError> {
let canonical = match fs::canonicalize(&path) { if path.starts_with("$/") {
path = find_std_path()
.join(&path[2..])
.to_string_lossy()
.into_owned();
}
let base_dir = Path::new(&self.loc.filename).parent().unwrap();
let resolved_path = base_dir.join(&path);
let canonical = match fs::canonicalize(&resolved_path) {
Ok(p) => p, Ok(p) => p,
Err(e) => { Err(e) => {
return error!(self.loc, format!("failed to resolve {}: {}", path, e)); return error!(self.loc, format!("failed to resolve {}: {}", path, e));
} }
}; };
if !self.included_paths.insert(canonical) { if !self.included_paths.insert(canonical.clone()) {
return Ok(()); return Ok(());
} }
let source = match fs::read_to_string(&path) { let meta = match std::fs::metadata(&canonical) {
Ok(x) => x,
Err(_) => {
return error!(self.loc, format!("failed to access {}", path));
}
};
if !meta.file_type().is_file() {
return error!(
self.loc,
format!("refusing to read {} because it is not a regular file", path)
);
}
let source = match fs::read_to_string(&canonical) {
Ok(x) => x, Ok(x) => x,
Err(_) => { Err(_) => {
return error!(self.loc, format!("failed to include {}", path)); return error!(self.loc, format!("failed to include {}", path));
} }
}; };
let filename = Path::new(&path).file_name().unwrap().to_str().unwrap(); let tokenizer = Tokenizer::new(
canonical.to_string_lossy().into_owned(),
let tokenizer = Tokenizer::new(filename.to_owned(), source, &mut *self.included_paths); source,
&mut *self.included_paths,
);
self.tokens.extend(tokenizer.tokenize()?); self.tokens.extend(tokenizer.tokenize()?);
self.tokens.pop(); // remove inner Eof self.tokens.pop(); // remove inner Eof
@@ -552,3 +577,15 @@ impl<'a> Tokenizer<'a> {
self.current >= self.source.len() self.current >= self.source.len()
} }
} }
fn find_std_path() -> PathBuf {
let path = std::env::current_exe().unwrap();
for dir in path.ancestors() {
let candidate = dir.join("std");
if candidate.is_dir() {
return candidate;
}
}
panic!("could not find zern std directory");
}

View File

@@ -1,15 +1,15 @@
use std::collections::HashMap; use std::collections::HashMap;
use crate::{ use crate::{
parser::{Expr, ExprKind, Params, Stmt}, parser::{Expr, ExprKind, Params, ScopeCall, Stmt, recursion_guard},
symbol_table::{FnParams, SymbolTable}, symbol_table::{FnParams, SymbolTable},
tokenizer::{TokenType, ZernError, error}, tokenizer::{Loc, TokenType, ZernError, error},
}; };
macro_rules! expect_type { macro_rules! expect_type {
($expr_type:expr, $expected:expr, $loc:expr) => {{ ($expr_type:expr, $expected:expr, $loc:expr) => {{
let actual = $expr_type; let actual = $expr_type;
if $expected != "any" && actual != "any" && actual != $expected { if $expected != "$" && actual != "$" && actual != $expected {
return error!( return error!(
$loc, $loc,
format!("expected type '{}', got {}", $expected, actual) format!("expected type '{}', got {}", $expected, actual)
@@ -20,7 +20,7 @@ macro_rules! expect_type {
macro_rules! expect_types { macro_rules! expect_types {
($expr_type:expr, [$( $expected:expr ),+], $loc:expr) => { ($expr_type:expr, [$( $expected:expr ),+], $loc:expr) => {
if $expr_type != "any" && $( $expr_type != $expected )&&+ { if $expr_type != "$" && $( $expr_type != $expected )&&+ {
return error!( return error!(
$loc, $loc,
format!( format!(
@@ -33,7 +33,7 @@ macro_rules! expect_types {
}; };
} }
static BUILTIN_TYPES: [&str; 8] = ["void", "u8", "i64", "f64", "str", "bool", "ptr", "any"]; static BUILTIN_TYPES: [&str; 8] = ["void", "u8", "i64", "f64", "str", "bool", "ptr", "opaque"];
pub struct Env { pub struct Env {
scopes: Vec<HashMap<String, String>>, scopes: Vec<HashMap<String, String>>,
@@ -73,6 +73,7 @@ pub struct TypeChecker<'a> {
symbol_table: &'a SymbolTable, symbol_table: &'a SymbolTable,
pub expr_types: HashMap<usize, String>, pub expr_types: HashMap<usize, String>,
current_function_return_type: String, current_function_return_type: String,
depth: usize,
} }
impl<'a> TypeChecker<'a> { impl<'a> TypeChecker<'a> {
@@ -81,6 +82,7 @@ impl<'a> TypeChecker<'a> {
symbol_table, symbol_table,
expr_types: HashMap::new(), expr_types: HashMap::new(),
current_function_return_type: String::new(), current_function_return_type: String::new(),
depth: 0,
} }
} }
@@ -89,31 +91,14 @@ impl<'a> TypeChecker<'a> {
Stmt::Expression(expr) => { Stmt::Expression(expr) => {
self.typecheck_expr(env, expr)?; self.typecheck_expr(env, expr)?;
} }
Stmt::Declare { Stmt::Declare { name, initializer } => {
name, let actual_type = self.typecheck_expr(env, initializer)?;
var_type,
initializer,
} => {
let mut actual_type = self.typecheck_expr(env, initializer)?;
if actual_type.contains(',') { if actual_type.contains(',') {
return error!( return error!(
&name.loc, &name.loc,
"cannot assign multi-return call to a single variable" "cannot assign multi-return call to a single variable"
); );
} }
if let Some(var_type) = var_type {
if !self.is_valid_type_name(&var_type.lexeme) {
return error!(
&name.loc,
"unrecognized type: ".to_owned() + &var_type.lexeme
);
}
expect_type!(actual_type.clone(), var_type.lexeme, var_type.loc);
if actual_type == "any" {
actual_type = var_type.lexeme.clone();
}
}
env.define_var(name.lexeme.clone(), actual_type); env.define_var(name.lexeme.clone(), actual_type);
} }
@@ -150,8 +135,9 @@ impl<'a> TypeChecker<'a> {
} }
ExprKind::MemberAccess { left, field } => { ExprKind::MemberAccess { left, field } => {
let left_type = self.typecheck_expr(env, left)?; let left_type = self.typecheck_expr(env, left)?;
let (base_name, generic_args) = parse_generic_type(&left_type);
let fields = match self.symbol_table.structs.get(&left_type) { let fields = match self.symbol_table.structs.get(base_name) {
Some(f) => f, Some(f) => f,
None => { None => {
return error!( return error!(
@@ -171,7 +157,13 @@ impl<'a> TypeChecker<'a> {
} }
}; };
expect_type!(value_type.clone(), f.field_type, field.loc); let field_type = if let Some(args) = generic_args {
substitute_type(&f.field_type, args[0])
} else {
f.field_type.clone()
};
expect_type!(value_type.clone(), field_type, field.loc);
} }
_ => return error!(&op.loc, "invalid assignment target"), _ => return error!(&op.loc, "invalid assignment target"),
} }
@@ -214,7 +206,7 @@ impl<'a> TypeChecker<'a> {
} => { } => {
expect_types!( expect_types!(
self.typecheck_expr(env, condition)?, self.typecheck_expr(env, condition)?,
["i64", "u8", "ptr", "bool"], ["i64", "u8", "ptr", "bool", "opaque"],
keyword.loc keyword.loc
); );
self.typecheck_stmt(env, then_branch)?; self.typecheck_stmt(env, then_branch)?;
@@ -366,6 +358,8 @@ impl<'a> TypeChecker<'a> {
} }
pub fn typecheck_expr(&mut self, env: &mut Env, expr: &Expr) -> Result<String, ZernError> { pub fn typecheck_expr(&mut self, env: &mut Env, expr: &Expr) -> Result<String, ZernError> {
recursion_guard!(self);
let expr_type = match &expr.kind { let expr_type = match &expr.kind {
ExprKind::Binary { left, op, right } => { ExprKind::Binary { left, op, right } => {
let left_type = self.typecheck_expr(env, left)?; let left_type = self.typecheck_expr(env, left)?;
@@ -436,7 +430,7 @@ impl<'a> TypeChecker<'a> {
let right_type = self.typecheck_expr(env, right)?; let right_type = self.typecheck_expr(env, right)?;
match op.token_type { match op.token_type {
TokenType::Minus => { TokenType::Minus => {
expect_types!(right_type, ["f64", "i64"], op.loc); expect_type!(right_type.clone(), "i64", op.loc);
Ok(right_type) Ok(right_type)
} }
TokenType::Bang => { TokenType::Bang => {
@@ -499,7 +493,7 @@ impl<'a> TypeChecker<'a> {
for arg in args { for arg in args {
self.typecheck_expr(env, arg)?; self.typecheck_expr(env, arg)?;
} }
Ok("any".into()) Ok("opaque".into())
} }
} else { } else {
// its an expression that evalutes to function address // its an expression that evalutes to function address
@@ -508,14 +502,19 @@ impl<'a> TypeChecker<'a> {
for arg in args { for arg in args {
self.typecheck_expr(env, arg)?; self.typecheck_expr(env, arg)?;
} }
Ok("any".into()) Ok("opaque".into())
} }
} }
ExprKind::ArrayLiteral(exprs) => { ExprKind::ArrayLiteral(exprs) => {
for expr in exprs { for expr in exprs {
self.typecheck_expr(env, expr)?; self.typecheck_expr(env, expr)?;
} }
if exprs.is_empty() {
Ok("Array".into()) Ok("Array".into())
} else {
let first_item_type = self.typecheck_expr(env, &exprs[0])?;
Ok(format!("Array<{}>", first_item_type))
}
} }
ExprKind::Index { ExprKind::Index {
expr, expr,
@@ -536,34 +535,42 @@ impl<'a> TypeChecker<'a> {
struct_name, struct_name,
use_heap: _, use_heap: _,
} => { } => {
if !self.symbol_table.structs.contains_key(&struct_name.lexeme) { let (base_name, _) = parse_generic_type(&struct_name.lexeme);
if !self.symbol_table.structs.contains_key(base_name) {
return error!( return error!(
&struct_name.loc, &struct_name.loc,
format!("unknown struct name: {}", &struct_name.lexeme) format!("unknown struct name: {}", base_name)
); );
} }
Ok(struct_name.lexeme.clone()) Ok(struct_name.lexeme.clone())
} }
ExprKind::MemberAccess { left, field } => { ExprKind::MemberAccess { left, field } => {
let left_type = self.typecheck_expr(env, left)?; let left_type = self.typecheck_expr(env, left)?;
let (base_name, generic_args) = parse_generic_type(&left_type);
let fields = match self.symbol_table.structs.get(&left_type) { let fields = match self.symbol_table.structs.get(base_name) {
Some(f) => f, Some(f) => f,
None => { None => {
return error!(&field.loc, format!("unknown struct type: {}", left_type)); return error!(&field.loc, format!("unknown struct type: {}", base_name));
} }
}; };
let field = match fields.get(&field.lexeme) { let field_info = match fields.get(&field.lexeme) {
Some(o) => o, Some(o) => o,
None => return error!(&field.loc, format!("unknown field: {}", &field.lexeme)), None => return error!(&field.loc, format!("unknown field: {}", &field.lexeme)),
}; };
Ok(field.field_type.clone()) let field_type = if let Some(args) = generic_args {
substitute_type(&field_info.field_type, args[0])
} else {
field_info.field_type.clone()
};
Ok(field_type)
} }
ExprKind::Cast { expr, type_name } => { ExprKind::Cast { expr, type_name } => {
let expr_type = self.typecheck_expr(env, expr)?; let expr_type = self.typecheck_expr(env, expr)?;
if expr_type != "any" && type_name.lexeme == "f64" { if expr_type != "opaque" && type_name.lexeme == "f64" {
return error!( return error!(
&type_name.loc, &type_name.loc,
"use _builtin_cvtsi2sd and _builtin_cvttsd2si to cast between integers and f64" "use _builtin_cvtsi2sd and _builtin_cvttsd2si to cast between integers and f64"
@@ -579,7 +586,8 @@ impl<'a> TypeChecker<'a> {
} }
ExprKind::MethodCall { expr, method, args } => { ExprKind::MethodCall { expr, method, args } => {
let receiver_type = self.typecheck_expr(env, expr)?; let receiver_type = self.typecheck_expr(env, expr)?;
let func_name = format!("{}.{}", receiver_type, method.lexeme); let (base_name, generic_args) = parse_generic_type(&receiver_type);
let func_name = format!("{}.{}", base_name, method.lexeme);
let func_type = match self.symbol_table.functions.get(&func_name) { let func_type = match self.symbol_table.functions.get(&func_name) {
Some(f) => f, Some(f) => f,
@@ -588,25 +596,26 @@ impl<'a> TypeChecker<'a> {
method.loc, method.loc,
format!( format!(
"method {} not found on on type {}", "method {} not found on on type {}",
method.lexeme, receiver_type method.lexeme, base_name
) )
); );
} }
}; };
let substitute = |s: &str| -> String {
if let Some(ref args) = generic_args {
substitute_type(s, args[0])
} else {
s.to_string()
}
};
match &func_type.params { match &func_type.params {
FnParams::Normal(params) => { FnParams::Normal(params) => {
if params.len() != args.len() + 1 { let substituted_params: Vec<String> =
return error!( params.iter().map(|p| substitute(p)).collect();
method.loc,
format!( if substituted_params.is_empty() || substituted_params[0] != receiver_type {
"expected {} arguments, got {}",
params.len() - 1,
args.len()
)
);
}
if params[0] != receiver_type {
return error!( return error!(
method.loc, method.loc,
format!( format!(
@@ -615,16 +624,30 @@ impl<'a> TypeChecker<'a> {
) )
); );
} }
for (i, arg) in args.iter().enumerate() { if substituted_params.len() != args.len() + 1 {
expect_type!(self.typecheck_expr(env, arg)?, params[i + 1], method.loc); return error!(
method.loc,
format!(
"expected {} arguments, got {}",
substituted_params.len() - 1,
args.len()
)
);
} }
Ok(func_type.return_type.clone()) for (i, arg) in args.iter().enumerate() {
expect_type!(
self.typecheck_expr(env, arg)?,
substituted_params[i + 1].as_str(),
method.loc
);
}
Ok(substitute(&func_type.return_type))
} }
FnParams::Variadic => { FnParams::Variadic => {
for arg in args { for arg in args {
self.typecheck_expr(env, arg)?; self.typecheck_expr(env, arg)?;
} }
Ok(func_type.return_type.clone()) Ok(substitute(&func_type.return_type))
} }
} }
} }
@@ -635,9 +658,22 @@ impl<'a> TypeChecker<'a> {
} }
fn is_valid_type_name(&self, name: &str) -> bool { fn is_valid_type_name(&self, name: &str) -> bool {
if name == "$" {
return true;
}
if name.contains(',') { if name.contains(',') {
return name.split(',').all(|part| self.is_valid_type_name(part)); return name.split(',').all(|part| self.is_valid_type_name(part));
} }
if name.contains('<') {
let (base, inner) = parse_generic_type(name);
if !self.symbol_table.structs.contains_key(base) {
return false;
}
if let Some(args) = inner {
return args.iter().all(|arg| self.is_valid_type_name(arg));
}
unreachable!();
}
if BUILTIN_TYPES.contains(&name) { if BUILTIN_TYPES.contains(&name) {
return true; return true;
} }
@@ -647,3 +683,37 @@ impl<'a> TypeChecker<'a> {
false false
} }
} }
fn parse_generic_type(s: &str) -> (&str, Option<Vec<&str>>) {
if let Some(lt_pos) = s.find('<') {
let base = &s[..lt_pos];
let close_pos = s.rfind('>').unwrap_or(s.len());
let inner = &s[lt_pos + 1..close_pos];
let mut args = Vec::new();
let mut depth = 0;
let mut start = 0;
for (i, ch) in inner.char_indices() {
match ch {
'<' => depth += 1,
'>' => depth -= 1,
',' if depth == 0 => {
args.push(&inner[start..i]);
start = i + 1;
}
_ => {}
}
}
args.push(&inner[start..]);
(base, Some(args))
} else {
(s, None)
}
}
fn substitute_type(type_str: &str, dollar_replacement: &str) -> String {
if type_str.contains('$') {
type_str.replace('$', dollar_replacement)
} else {
type_str.to_string()
}
}

View File

@@ -1,30 +1,28 @@
include "std/mem.zr" include "mem.zr"
struct Array struct Array
data: ptr data: ptr
size: i64 size: i64
capacity: i64 capacity: i64
func Array.new_preallocated_and_zeroed[size: i64] : Array func Array.preallocate_and_zero[xs: Array<$>, size: i64] : void
xs := new* Array
if size > 0 if size > 0
xs->data = mem.alloc(size * 8) xs->data = mem.alloc(size * 8)
mem.zero(xs->data, size * 8) mem.zero(xs->data, size * 8)
xs->size = size xs->size = size
xs->capacity = size xs->capacity = size
return xs
func Array.nth[xs: Array, n: i64] : any func Array.nth[xs: Array<$>, n: i64] : $
if n < 0 || n >= xs->size if n < 0 || n >= xs->size
panic("Array.nth out of bounds") panic("Array.nth out of bounds")
return mem.read64(xs->data + n * 8) return mem.read64(xs->data + n * 8)
func Array.set[xs: Array, n: i64, x: any] : void func Array.set[xs: Array<$>, n: i64, x: $] : void
if n < 0 || n >= xs->size if n < 0 || n >= xs->size
panic("Array.set out of bounds") panic("Array.set out of bounds")
mem.write64(xs->data + n * 8, x) mem.write64(xs->data + n * 8, x)
func Array.push[xs: Array, x: any] : void func Array.push[xs: Array<$>, x: $] : void
if xs->size == xs->capacity if xs->size == xs->capacity
new_capacity := 4 new_capacity := 4
if xs->capacity != 0 if xs->capacity != 0
@@ -35,109 +33,112 @@ func Array.push[xs: Array, x: any] : void
mem.write64(xs->data + xs->size * 8, x) mem.write64(xs->data + xs->size * 8, x)
xs->size += 1 xs->size += 1
func Array.free[xs: Array] : void func Array.free[xs: Array<$>] : void
if xs->data != 0 if xs->data != 0
xs->data->free() xs->data->free()
mem.free(xs) (xs as ptr)->free()
func Array.free_with_items[xs: Array] : void func Array.free_with_items[xs: Array<$>] : void
if xs->data != 0 if xs->data != 0
for i in 0..xs->size for i in 0..xs->size
mem.free(xs->nth(i)) (xs->nth(i) as ptr)->free()
xs->data->free() xs->data->free()
mem.free(xs) (xs as ptr)->free()
func Array.pop[xs: Array] : any func Array.pop[xs: Array<$>] : $
if xs->size == 0 if xs->size == 0
panic("Array.pop on empty array") panic("Array.pop on empty array")
x : any = Array.last(xs) x := Array.last(xs)
xs->size = xs->size - 1 xs->size = xs->size - 1
return x return x
func Array.last[xs: Array] : any func Array.last[xs: Array<$>] : $
if xs->size == 0 if xs->size == 0
panic("Array.last on empty array") panic("Array.last on empty array")
return xs->nth(xs->size - 1) return xs->nth(xs->size - 1)
func Array.slice[xs: Array, start: i64, length: i64] : Array func Array.slice[xs: Array<$>, start: i64, length: i64] : Array<$>
if start < 0 || length < 0 || start + length > xs->size if start < 0 || length < 0 || start + length > xs->size
panic("Array.slice out of bounds") panic("Array.slice out of bounds")
new_array := Array.new_preallocated_and_zeroed(length) new_array := [] as Array<$>
new_array->preallocate_and_zero(length)
mem.copy(xs->data + start * 8, new_array->data, length * 8) mem.copy(xs->data + start * 8, new_array->data, length * 8)
return new_array return new_array
func Array.concat[a: Array, b: Array] : Array func Array.concat[a: Array<$>, b: Array<$>] : Array<$>
new_array := Array.new_preallocated_and_zeroed(a->size + b->size) new_array := [] as Array<$>
new_array->preallocate_and_zero(a->size + b->size)
mem.copy(a->data, new_array->data, a->size * 8) mem.copy(a->data, new_array->data, a->size * 8)
mem.copy(b->data, new_array->data + a->size * 8, b->size * 8) mem.copy(b->data, new_array->data + a->size * 8, b->size * 8)
return new_array return new_array
func Array.quicksort[arr: Array] : void func Array.quicksort[arr: Array<i64>] : void
arr->_do_quicksort(0, arr->size - 1) arr->_do_quicksort(0, arr->size - 1)
func Array._do_quicksort[arr: Array, low: i64, high: i64] : void func Array._do_quicksort[arr: Array<i64>, low: i64, high: i64] : void
if low < high if low < high
i := arr->_partition(low, high) i := arr->_partition(low, high)
arr->_do_quicksort(low, i - 1) arr->_do_quicksort(low, i - 1)
arr->_do_quicksort(i + 1, high) arr->_do_quicksort(i + 1, high)
func Array._partition[arr: Array, low: i64, high: i64] : i64 func Array._partition[arr: Array<i64>, low: i64, high: i64] : i64
pivot : i64 = arr->nth(high) pivot := arr->nth(high)
i := low - 1 i := low - 1
for j in (low)..high for j in (low)..high
if arr->nth(j) as i64 <= pivot if arr->nth(j) as i64 <= pivot
i += 1 i += 1
temp : i64 = arr->nth(i) temp := arr->nth(i)
arr->set(i, arr->nth(j)) arr->set(i, arr->nth(j))
arr->set(j, temp) arr->set(j, temp)
temp : i64 = arr->nth(i + 1) temp := arr->nth(i + 1)
arr->set(i + 1, arr->nth(high)) arr->set(i + 1, arr->nth(high))
arr->set(high, temp) arr->set(high, temp)
return i + 1 return i + 1
func Array.contains_str[arr: Array, s: str] : bool func Array.contains_str[arr: Array<str>, s: str] : bool
for i in 0..arr->size for i in 0..arr->size
if (arr->nth(i) as str)->equal(s) if (arr->nth(i) as str)->equal(s)
return true return true
return false return false
func Array.count[arr: Array, item: any] : i64 func Array.count[arr: Array<$>, item: $] : i64
count := 0 count := 0
for i in 0..arr->size for i in 0..arr->size
if arr->nth(i) == item if arr->nth(i) == item
count += 1 count += 1
return count return count
func Array.map[arr: Array, fn: ptr] : Array func Array.map[arr: Array<$>, fn: ptr] : Array<$>
out := Array.new_preallocated_and_zeroed(arr->size) out := [] as Array<$>
out->preallocate_and_zero(arr->size)
for i in 0..arr->size for i in 0..arr->size
out->set(i, fn(arr->nth(i))) out->set(i, fn(arr->nth(i)))
return out return out
func Array.filter[arr: Array, fn: ptr] : Array func Array.filter[arr: Array<$>, fn: ptr] : Array<$>
out := [] out := [] as Array<$>
for i in 0..arr->size for i in 0..arr->size
if fn(arr->nth(i)) if fn(arr->nth(i)) as bool
out->push(arr->nth(i)) out->push(arr->nth(i))
return out return out
func Array.reduce[arr: Array, fn: ptr, acc: any] : any func Array.reduce[arr: Array<$>, fn: ptr, acc: $] : $
for i in 0..arr->size for i in 0..arr->size
acc = fn(acc, arr->nth(i)) acc = fn(acc, arr->nth(i))
return acc return acc
func str.split[haystack: str, needle: str]: Array func str.split[haystack: str, needle: str]: Array<str>
haystack_len := haystack->len() haystack_len := haystack->len()
needle_len := needle->len() needle_len := needle->len()
result := [] result := [] as Array<str>
if !needle_len if !needle_len
if !haystack_len if !haystack_len
return result return result
else else
for i in 0..haystack_len for i in 0..haystack_len
result->push(haystack->substr(i, 1)) result->push(haystack->substr_n(i, 1))
return result return result
start := 0 start := 0
@@ -150,33 +151,34 @@ func str.split[haystack: str, needle: str]: Array
match = false match = false
break break
if match if match
result->push(haystack->substr(start, i - start)) result->push(haystack->substr_n(start, i - start))
start = i + needle_len start = i + needle_len
i += needle_len i += needle_len
continue continue
i += 1 i += 1
result->push(haystack->substr(start, haystack_len - start)) result->push(haystack->substr_n(start, haystack_len - start))
return result return result
const HashMap._TABLE_SIZE = 100 const HashMap._TABLE_SIZE = 100
struct HashMap struct HashMap
table: Array table: Array<HashMap._Node>
struct HashMap._Node struct HashMap._Node
key: str key: str
value: any value: $
next: HashMap._Node next: HashMap._Node
func HashMap.new[] : HashMap func HashMap.new[] : HashMap
map := new* HashMap map := new* HashMap
map->table = Array.new_preallocated_and_zeroed(HashMap._TABLE_SIZE) map->table = [] as Array<HashMap._Node>
map->table->preallocate_and_zero(HashMap._TABLE_SIZE)
return map return map
func HashMap.insert[map: HashMap, key: str, value: any] : void func HashMap.insert[map: HashMap<$>, key: str, value: $] : void
index := HashMap._djb2(key) index := HashMap._djb2(key)
current : HashMap._Node = map->table->nth(index) current := map->table->nth(index)
while current as ptr while current as ptr
if current->key->equal(key) if current->key->equal(key)
@@ -190,20 +192,20 @@ func HashMap.insert[map: HashMap, key: str, value: any] : void
new_node->next = map->table->nth(index) new_node->next = map->table->nth(index)
map->table->set(index, new_node) map->table->set(index, new_node)
func HashMap.get[map: HashMap, key: str] : any, bool func HashMap.get[map: HashMap<$>, key: str] : $, bool
index := HashMap._djb2(key) index := HashMap._djb2(key)
current : HashMap._Node = map->table->nth(index) current := map->table->nth(index)
while current as ptr while current as ptr
if current->key->equal(key) if current->key->equal(key)
return current->value, true return current->value, true
current = current->next current = current->next
return 0 as any, false return 0 as $, false
func HashMap.delete[map: HashMap, key: str] : void func HashMap.delete[map: HashMap<$>, key: str] : void
index := HashMap._djb2(key) index := HashMap._djb2(key)
current : HashMap._Node = map->table->nth(index) current := map->table->nth(index)
prev := 0 as HashMap._Node prev := 0 as HashMap._Node
while current as ptr while current as ptr
@@ -214,27 +216,36 @@ func HashMap.delete[map: HashMap, key: str] : void
map->table->set(index, current->next) map->table->set(index, current->next)
current->key->free() current->key->free()
mem.free(current) (current as ptr)->free()
return return
prev = current prev = current
current = current->next current = current->next
func HashMap.keys[map: HashMap<$>] : Array<str>
out := [] as Array<str>
for i in 0..HashMap._TABLE_SIZE
current := map->table->nth(i)
while current as ptr
out->push(current->key)
current = current->next
return out
func HashMap.free_with_keys[map: HashMap<$>] : void
for i in 0..HashMap._TABLE_SIZE
current := map->table->nth(i)
while current as ptr
tmp := current
current = current->next
tmp->key->free()
(tmp as ptr)->free()
map->table->free()
(map as ptr)->free()
func HashMap._djb2[key: str] : i64 func HashMap._djb2[key: str] : i64
hash := 5381 hash := 5381
for i in 0..key->len() for i in 0..key->len()
hash = ((hash << 5) + hash) + key[i] hash = ((hash << 5) + hash) + key[i]
hash = (hash & 0x7fffffffffffffff) // prevent negative hash = (hash & 0x7fffffffffffffff) // prevent negative
return hash % HashMap._TABLE_SIZE return hash % HashMap._TABLE_SIZE
func HashMap.free[map: HashMap] : void
for i in 0..HashMap._TABLE_SIZE
current : HashMap._Node = map->table->nth(i)
while current as ptr
tmp := current
current = current->next
tmp->key->free()
mem.free(tmp)
map->table->free()
mem.free(map)

View File

@@ -1,14 +0,0 @@
include "std/linux_syscalls.zr"
include "std/posix.zr"
// weird like that so num doesnt depend on io
func panic[msg: str] : void
len := 0
while msg[len]
len += 1
_builtin_syscall(SYS_write, 2, "PANIC: ", 7)
_builtin_syscall(SYS_write, 2, msg, len)
_builtin_syscall(SYS_write, 2, "\n", 1)
// for gdb backtrace
_builtin_syscall(SYS_kill, _builtin_syscall(SYS_getpid), SIGABRT)
_builtin_syscall(SYS_exit, 1)

View File

@@ -1,4 +1,15 @@
include "std/str.zr" include "str.zr"
include "os.zr"
func panic[msg: str] : void
io.printf("PANIC: %s\n", msg)
// for gdb backtrace
_builtin_syscall(SYS_kill, os.getpid(), SIGABRT)
os.exit(1)
func assert[cond: bool, msg: str] : void
if !cond
panic(msg)
func io.printf[..] : void func io.printf[..] : void
s := _var_arg(0) as ptr s := _var_arg(0) as ptr
@@ -85,9 +96,7 @@ func io.read_line[] : str
if c == '\n' if c == '\n'
break break
b->append_char(c) b->append_char(c)
s := b->build() return b->build_and_free_buffer()
b->destroy()
return s
func io.read_text_file[path: str] : str, bool func io.read_text_file[path: str] : str, bool
fd := _builtin_syscall(SYS_openat, AT_FDCWD, path, O_RDONLY, 0) fd := _builtin_syscall(SYS_openat, AT_FDCWD, path, O_RDONLY, 0)
@@ -128,7 +137,7 @@ func io.read_binary_file[path: str] : Blob, bool
return buf, true return buf, true
func io.write_file[path: str, content: str] : bool func io.write_text_file[path: str, content: str] : bool
return io.write_binary_file(path, content as ptr, content->len()) return io.write_binary_file(path, content as ptr, content->len())
func io.write_binary_file[path: str, content: ptr, size: i64] : bool func io.write_binary_file[path: str, content: ptr, size: i64] : bool

203
std/json.zr Normal file
View File

@@ -0,0 +1,203 @@
include "containers.zr"
const json.OBJECT = 0
const json.ARRAY = 1
const json.STRING = 2
const json.NUMBER = 3
const json.NULL = 4
const json.BOOL = 5
struct json.Value
type: i64
value: opaque
func json.Value.dump[v: json.Value] : str
s := new str.Builder
if v->type == json.OBJECT
map := v->value as HashMap<json.Value>
keys := map->keys()
s->append_char('{')
for i in 0..keys->size
if i > 0
s->append_char(',')
s->append_char('"')
s->append(keys->nth(i))
s->append_char('"')
s->append_char(':')
value, _ := map->get(keys->nth(i))
s->append(value->dump())
s->append_char('}')
keys->free()
else if v->type == json.ARRAY
arr := v->value as Array<json.Value>
s->append_char('[')
for i in 0..arr->size
if i > 0
s->append_char(',')
s->append(arr->nth(i)->dump())
s->append_char(']')
else if v->type == json.STRING
// TODO: escape sequences
s->append_char('"')
s->append(v->value as str)
s->append_char('"')
else if v->type == json.NUMBER
s->append((v->value as i64)->to_str())
else if v->type == json.NULL
s->append("null")
else if v->type == json.BOOL
if v->value as bool
s->append("true")
else
s->append("false")
else
panic("json.Value.dump: unknown value type")
return s->build_and_free_buffer()
func json.Value.free[v: json.Value] : void
if v->type == json.OBJECT
map := v->value as HashMap<json.Value>
keys := map->keys()
for i in 0..keys->size
value, _ := map->get(keys->nth(i))
value->free()
keys->free()
map->free_with_keys()
else if v->type == json.ARRAY
arr := v->value as Array<json.Value>
for i in 0..arr->size
arr->nth(i)->free()
arr->free()
else if v->type == json.STRING
(v->value as str)->free()
(v as ptr)->free()
func json.val[x: opaque] : opaque
return (x as json.Value)->value
func json.parse[s: str] : json.Value
i := 0
return json._parse_value(s, ^i)
func json._parse_value[s: str, i: ptr] : json.Value
out := new* json.Value
json._skip_whitespace(s, i)
if s[mem.read64(i)] == 0
panic("json.parse: unexpected EOF")
if s[mem.read64(i)] == '{'
mem.write64(i, mem.read64(i) + 1)
json._skip_whitespace(s, i)
out->type = json.OBJECT
out->value = HashMap.new() as opaque
if s[mem.read64(i)] != '}'
while true
json._skip_whitespace(s, i)
key := json._parse_string(s, i)
json._skip_whitespace(s, i)
if s[mem.read64(i)] != ':'
panic("json.parse: expected ':'")
mem.write64(i, mem.read64(i) + 1)
json._skip_whitespace(s, i)
value := json._parse_value(s, i)
(out->value as HashMap<json.Value>)->insert(key, value)
key->free()
json._skip_whitespace(s, i)
if s[mem.read64(i)] == ','
mem.write64(i, mem.read64(i) + 1)
else
break
json._skip_whitespace(s, i)
if s[mem.read64(i)] != '}'
panic("json.parse: expected '}'")
mem.write64(i, mem.read64(i) + 1)
else if s[mem.read64(i)] == '['
mem.write64(i, mem.read64(i) + 1)
json._skip_whitespace(s, i)
out->type = json.ARRAY
out->value = [] as opaque
while s[mem.read64(i)] != ']'
json._skip_whitespace(s, i)
(out->value as Array<json.Value>)->push(json._parse_value(s, i))
json._skip_whitespace(s, i)
if s[mem.read64(i)] == ','
mem.write64(i, mem.read64(i) + 1)
else
break
json._skip_whitespace(s, i)
if s[mem.read64(i)] != ']'
panic("json.parse: expected ']'")
mem.write64(i, mem.read64(i) + 1)
else if s[mem.read64(i)] == '"'
out->type = json.STRING
out->value = json._parse_string(s, i) as opaque
else if s[mem.read64(i)]->is_digit() || s[mem.read64(i)] == '-'
start := mem.read64(i)
if s[mem.read64(i)] == '-'
mem.write64(i, mem.read64(i) + 1)
while s[mem.read64(i)]->is_digit()
mem.write64(i, mem.read64(i) + 1)
// TODO: float support once str.parse_f64 is a thing
if s[mem.read64(i)] == '.'
panic("json.parse: parsing floats not implemented yet")
len := mem.read64(i) - start
num_str := s->substr_n(start, len)
out->type = json.NUMBER
out->value = num_str->parse_i64() as opaque
num_str->free()
else if s[mem.read64(i)] == 'n' && s[mem.read64(i)+1] == 'u' && s[mem.read64(i)+2] == 'l' && s[mem.read64(i)+3] == 'l'
out->type = json.NULL
mem.write64(i, mem.read64(i) + 4)
else if s[mem.read64(i)] == 't' && s[mem.read64(i)+1] == 'r' && s[mem.read64(i)+2] == 'u' && s[mem.read64(i)+3] == 'e'
out->type = json.BOOL
out->value = true as opaque
mem.write64(i, mem.read64(i) + 4)
else if s[mem.read64(i)] == 'f' && s[mem.read64(i)+1] == 'a' && s[mem.read64(i)+2] == 'l' && s[mem.read64(i)+3] == 's' && s[mem.read64(i)+4] == 'e'
out->type = json.BOOL
out->value = false as opaque
mem.write64(i, mem.read64(i) + 5)
else
panic("json.parse: unexpected character")
return out
func json._parse_string[s: str, i: ptr] : str
if s[mem.read64(i)] != '"'
panic("json.parse: expected '\"'")
mem.write64(i, mem.read64(i) + 1)
start := mem.read64(i)
// TODO: escape sequences
while s[mem.read64(i)] != '"'
if s[mem.read64(i)] == 0
panic("json.parse: unexpected EOF")
mem.write64(i, mem.read64(i) + 1)
len := mem.read64(i) - start
mem.write64(i, mem.read64(i) + 1)
return s->substr_n(start, len)
func json._skip_whitespace[s: str, i: ptr] : void
while s[mem.read64(i)]->is_whitespace()
mem.write64(i, mem.read64(i) + 1)

View File

@@ -1,5 +1,5 @@
include "std/linux_syscalls.zr" include "linux_syscalls.zr"
include "std/num.zr" include "num.zr"
const MEM_BLOCK_SIZE = 32 const MEM_BLOCK_SIZE = 32
@@ -23,7 +23,7 @@ func mem.Block._split[blk: mem.Block, needed: i64] : void
if blk->next as ptr if blk->next as ptr
blk->next->prev = new_blk blk->next->prev = new_blk
else else
mem.write64(_builtin_heap_tail(), new_blk) mem.write64(_builtin_heap_tail(), new_blk as ptr as i64)
blk->size = needed blk->size = needed
blk->next = new_blk blk->next = new_blk
@@ -33,7 +33,7 @@ func mem._request_space[size: i64] : mem.Block
alloc_size := (needed + 4095) & -4096 alloc_size := (needed + 4095) & -4096
blk := _builtin_syscall(SYS_mmap, 0, alloc_size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) as mem.Block blk := _builtin_syscall(SYS_mmap, 0, alloc_size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) as mem.Block
if (blk as ptr as i64) == -1 if (blk as ptr as i64) == MAP_FAILED
panic("mem._request_space: failed to mmap") panic("mem._request_space: failed to mmap")
blk->size = alloc_size - MEM_BLOCK_SIZE blk->size = alloc_size - MEM_BLOCK_SIZE
@@ -46,7 +46,7 @@ func mem._request_space[size: i64] : mem.Block
tail->next = blk tail->next = blk
blk->prev = tail blk->prev = tail
mem.write64(_builtin_heap_tail(), blk) mem.write64(_builtin_heap_tail(), blk as ptr as i64)
return blk return blk
func mem.alloc[size: i64] : ptr func mem.alloc[size: i64] : ptr
@@ -66,15 +66,12 @@ func mem.alloc[size: i64] : ptr
blk := mem._request_space(size) blk := mem._request_space(size)
if !mem.read64(_builtin_heap_head()) if !mem.read64(_builtin_heap_head())
mem.write64(_builtin_heap_head(), blk) mem.write64(_builtin_heap_head(), blk as ptr as i64)
blk->_split(size) blk->_split(size)
return blk as ptr + MEM_BLOCK_SIZE return blk as ptr + MEM_BLOCK_SIZE
func mem.free[x: any] : void
ptr.free(x as ptr)
func ptr.free[x: ptr] : void func ptr.free[x: ptr] : void
if x == 0 if x == 0
return return
@@ -94,7 +91,7 @@ func ptr.free[x: ptr] : void
if next->next as ptr if next->next as ptr
next->next->prev = blk next->next->prev = blk
if mem.read64(_builtin_heap_tail()) == next as ptr if mem.read64(_builtin_heap_tail()) == next as ptr
mem.write64(_builtin_heap_tail(), blk) mem.write64(_builtin_heap_tail(), blk as ptr as i64)
prev := blk->prev prev := blk->prev
if prev as ptr && prev->free if prev as ptr && prev->free
@@ -105,7 +102,7 @@ func ptr.free[x: ptr] : void
if blk->next as ptr if blk->next as ptr
blk->next->prev = prev blk->next->prev = prev
if mem.read64(_builtin_heap_tail()) == blk as ptr if mem.read64(_builtin_heap_tail()) == blk as ptr
mem.write64(_builtin_heap_tail(), prev) mem.write64(_builtin_heap_tail(), prev as ptr as i64)
blk = prev blk = prev
block_total := blk->size + MEM_BLOCK_SIZE block_total := blk->size + MEM_BLOCK_SIZE
@@ -113,11 +110,11 @@ func ptr.free[x: ptr] : void
if blk->prev as ptr if blk->prev as ptr
blk->prev->next = blk->next blk->prev->next = blk->next
else else
mem.write64(_builtin_heap_head(), blk->next) mem.write64(_builtin_heap_head(), blk->next as ptr as i64)
if blk->next as ptr if blk->next as ptr
blk->next->prev = blk->prev blk->next->prev = blk->prev
else else
mem.write64(_builtin_heap_tail(), blk->prev) mem.write64(_builtin_heap_tail(), blk->prev as ptr as i64)
_builtin_syscall(SYS_munmap, blk, block_total) _builtin_syscall(SYS_munmap, blk, block_total)
func ptr.realloc[x: ptr, new_size: i64] : ptr func ptr.realloc[x: ptr, new_size: i64] : ptr
@@ -149,7 +146,7 @@ func ptr.realloc[x: ptr, new_size: i64] : ptr
if next->next as ptr if next->next as ptr
next->next->prev = blk next->next->prev = blk
if mem.read64(_builtin_heap_tail()) == next as ptr if mem.read64(_builtin_heap_tail()) == next as ptr
mem.write64(_builtin_heap_tail(), blk) mem.write64(_builtin_heap_tail(), blk as ptr as i64)
blk->_split(new_size) blk->_split(new_size)
return x return x
@@ -222,7 +219,7 @@ func mem.write16be[x: ptr, d: i64] : void
x[0] = (d >> 8) & 0xff x[0] = (d >> 8) & 0xff
x[1] = d & 0xff x[1] = d & 0xff
func mem.write64[x: ptr, d: any] : void func mem.write64[x: ptr, d: i64] : void
_builtin_set64(x, d) _builtin_set64(x, d)
struct Blob struct Blob
@@ -237,4 +234,4 @@ func Blob.alloc[size: i64] : Blob
func Blob.free[buf: Blob] : void func Blob.free[buf: Blob] : void
buf->data->free() buf->data->free()
mem.free(buf) (buf as ptr)->free()

View File

@@ -1,4 +1,4 @@
include "std/os.zr" include "os.zr"
const AF_INET = 2 const AF_INET = 2
const SOCK_STREAM = 1 const SOCK_STREAM = 1
@@ -22,7 +22,7 @@ func net.listen[host: str, port: i64] : i64, bool
_builtin_syscall(SYS_close, s) _builtin_syscall(SYS_close, s)
return -1, false return -1, false
~packed_host, ok := net.resolve(host) packed_host, ok := net.resolve(host)
if !ok if !ok
return -1, false return -1, false
@@ -44,7 +44,7 @@ func net.connect[host: str, port: i64] : i64, bool
if s < 0 if s < 0
return -1, false return -1, false
~packed_host, ok := net.resolve(host) packed_host, ok := net.resolve(host)
if !ok if !ok
return -1, false return -1, false
@@ -101,18 +101,18 @@ func net.UDPSocket.receive[s: net.UDPSocket, size: i64] : net.UDPPacket
func net.UDPSocket.close_and_free[s: net.UDPSocket] : void func net.UDPSocket.close_and_free[s: net.UDPSocket] : void
_builtin_syscall(SYS_close, s->fd) _builtin_syscall(SYS_close, s->fd)
s->addr->free() s->addr->free()
mem.free(s) (s as ptr)->free()
func net.create_udp_client[host: str, port: i64] : net.UDPSocket, bool func net.create_udp_client[host: str, port: i64] : net.UDPSocket, bool
s := new* net.UDPSocket s := new* net.UDPSocket
~packed_host, ok := net.resolve(host) packed_host, ok := net.resolve(host)
if !ok if !ok
return 0 as net.UDPSocket, false return 0 as net.UDPSocket, false
s->fd = _builtin_syscall(SYS_socket, AF_INET, SOCK_DGRAM, 0) s->fd = _builtin_syscall(SYS_socket, AF_INET, SOCK_DGRAM, 0)
if s->fd < 0 if s->fd < 0
mem.free(s) (s as ptr)->free()
return 0 as net.UDPSocket, false return 0 as net.UDPSocket, false
s->addr = mem.alloc(16) s->addr = mem.alloc(16)
@@ -120,7 +120,7 @@ func net.create_udp_client[host: str, port: i64] : net.UDPSocket, bool
return s, true return s, true
func net.create_udp_server[host: str, port: i64] : net.UDPSocket, bool func net.create_udp_server[host: str, port: i64] : net.UDPSocket, bool
~s, ok := net.create_udp_client(host, port) s, ok := net.create_udp_client(host, port)
if !ok if !ok
return 0 as net.UDPSocket, false return 0 as net.UDPSocket, false
@@ -141,7 +141,7 @@ struct net.UDPPacket
func net.UDPPacket.free[pkt: net.UDPPacket] : void func net.UDPPacket.free[pkt: net.UDPPacket] : void
pkt->data->free() pkt->data->free()
pkt->source_addr->free() pkt->source_addr->free()
mem.free(pkt) (pkt as ptr)->free()
func net.resolve[domain: str] : i64, bool func net.resolve[domain: str] : i64, bool
// if domain is already an ip, skip dns resolution // if domain is already an ip, skip dns resolution
@@ -149,7 +149,7 @@ func net.resolve[domain: str] : i64, bool
if parts->size == 4 if parts->size == 4
valid := true valid := true
for i in 0..4 for i in 0..4
p := parts->nth(i) as str p := parts->nth(i)
if p->len() < 1 || p->len() > 3 if p->len() < 1 || p->len() > 3
valid = false valid = false
break break
@@ -160,10 +160,10 @@ func net.resolve[domain: str] : i64, bool
if !valid if !valid
break break
if valid if valid
a := (parts->nth(0) as str)->parse_i64() a := parts->nth(0)->parse_i64()
b := (parts->nth(1) as str)->parse_i64() b := parts->nth(1)->parse_i64()
c := (parts->nth(2) as str)->parse_i64() c := parts->nth(2)->parse_i64()
d := (parts->nth(3) as str)->parse_i64() d := parts->nth(3)->parse_i64()
if a >= 0 && a <= 255 && b >= 0 && b <= 255 && c >= 0 && c <= 255 && d >= 0 && d <= 255 if a >= 0 && a <= 255 && b >= 0 && b <= 255 && c >= 0 && c <= 255 && d >= 0 && d <= 255
parts->free_with_items() parts->free_with_items()
return net.pack_addr(a, b, c, d), true return net.pack_addr(a, b, c, d), true
@@ -172,7 +172,7 @@ func net.resolve[domain: str] : i64, bool
query := net.build_dns_query(domain, DNS_TYPE_A) query := net.build_dns_query(domain, DNS_TYPE_A)
// TODO: this probably shouldnt be hardcoded // TODO: this probably shouldnt be hardcoded
~s, ok := net.create_udp_client("1.1.1.1", 53) s, ok := net.create_udp_client("1.1.1.1", 53)
if !ok if !ok
query->free() query->free()
return -1, false return -1, false

View File

@@ -1,4 +1,4 @@
include "std/core.zr" include "io.zr"
func i64.abs[n: i64] : i64 func i64.abs[n: i64] : i64
if n == -9223372036854775808 if n == -9223372036854775808
@@ -51,7 +51,7 @@ func i64.to_str_buf[n: i64, buf: ptr] : void
buf[1] = 0 buf[1] = 0
return return
neg : bool = n < 0 neg := n < 0
if neg if neg
// MIN_I64 will fail but i so dont care // MIN_I64 will fail but i so dont care
n = -n n = -n
@@ -97,6 +97,16 @@ func i64.to_hex_str_buf[n: i64, buf: ptr] : void
buf[len] = 0 buf[len] = 0
func i64.to_str[n: i64] : str
out := mem.alloc(21)
n->to_str_buf(out)
return out as str
func i64.to_hex_str[n: i64] : str
out := mem.alloc(17)
n->to_hex_str_buf(out)
return out as str
func f64.to_str_buf[x: i64, buf: ptr] : void func f64.to_str_buf[x: i64, buf: ptr] : void
bits := x bits := x
sign := (bits >> 63) & 1 sign := (bits >> 63) & 1

View File

@@ -1,7 +1,7 @@
include "std/posix.zr" include "posix.zr"
include "std/linux_syscalls.zr" include "linux_syscalls.zr"
include "std/str.zr" include "str.zr"
include "std/containers.zr" include "containers.zr"
func os.exit[code: i64] : void func os.exit[code: i64] : void
_builtin_syscall(SYS_exit, code) _builtin_syscall(SYS_exit, code)
@@ -9,7 +9,10 @@ func os.exit[code: i64] : void
func os.getpid[] : i64 func os.getpid[] : i64
return _builtin_syscall(SYS_getpid) return _builtin_syscall(SYS_getpid)
func os.getenv[name: str] : str func os.arg[argv: ptr, n: i64] : str
return mem.read64(argv + n * 8) as str
func os.getenv[name: str] : str, bool
name_len := name->len() name_len := name->len()
i := 0 i := 0
while true while true
@@ -17,15 +20,24 @@ func os.getenv[name: str] : str
if entry as ptr == 0 if entry as ptr == 0
break break
if entry->equal_n(name, name_len) && entry[name_len] == '=' if entry->equal_n(name, name_len) && entry[name_len] == '='
return (entry as ptr + name_len + 1) as str return (entry as ptr + name_len + 1) as str, true
i += 1 i += 1
return "" return 0 as str, false
func os.basename[path: str] : str func os.basename[path: str] : str
i := path->len() - 1 len := path->len()
end := len
while end > 0 && path[end - 1] == '/'
end -= 1
if end == 0
return "/"
i := end - 1
while i >= 0 && path[i] != '/' while i >= 0 && path[i] != '/'
i -= 1 i -= 1
return path->substr(i + 1, path->len() - i - 1)
return path->substr_n(i + 1, end - i - 1)
struct os.Timespec struct os.Timespec
tv_sec: i64 tv_sec: i64
@@ -87,6 +99,15 @@ func os.run_shell_command[command: str] : i64, bool
func os.file_exists[path: str] : bool func os.file_exists[path: str] : bool
return _builtin_syscall(SYS_faccessat, AT_FDCWD, path, F_OK, 0) == 0 return _builtin_syscall(SYS_faccessat, AT_FDCWD, path, F_OK, 0) == 0
func os.get_file_size[path: str] : i64, bool
st := _stackalloc(256) // it has 21 mixed-size fields so ptr for now
rc := _builtin_syscall(SYS_newfstatat, AT_FDCWD, path, st, 0)
if rc != 0
return 0, false
return mem.read64(st + 48), true
func os.is_a_directory[path: str] : bool func os.is_a_directory[path: str] : bool
st := _stackalloc(256) // it has 21 mixed-size fields so ptr for now st := _stackalloc(256) // it has 21 mixed-size fields so ptr for now
@@ -96,26 +117,26 @@ func os.is_a_directory[path: str] : bool
return (mem.read32(st + 24) & S_IFMT) == S_IFDIR return (mem.read32(st + 24) & S_IFMT) == S_IFDIR
func os.list_directory[path: str] : Array, bool func os.list_directory[path: str] : Array<str>, bool
fd := _builtin_syscall(SYS_openat, AT_FDCWD, path, O_RDONLY, 0) fd := _builtin_syscall(SYS_openat, AT_FDCWD, path, O_RDONLY, 0)
if fd < 0 if fd < 0
return 0 as Array, false return 0 as Array<str>, false
files := [] files := [] as Array<str>
buf := _stackalloc(1024) buf := _stackalloc(1024)
while true while true
n := _builtin_syscall(SYS_getdents64, fd, buf, 1024) n := _builtin_syscall(SYS_getdents64, fd, buf, 1024)
if n < 0 if n < 0
files->free_with_items() files->free_with_items()
_builtin_syscall(SYS_close, fd) _builtin_syscall(SYS_close, fd)
return 0 as Array, false return 0 as Array<str>, false
else if n == 0 else if n == 0
break break
pos := 0 pos := 0
while pos < n while pos < n
len := mem.read16(buf + pos + 16) len := mem.read16(buf + pos + 16)
name : ptr = buf + pos + 19 name := buf + pos + 19
if name[0] if name[0]
skip := false skip := false
// skip if name is exactly '.' or '..' // skip if name is exactly '.' or '..'

View File

@@ -8,10 +8,15 @@ const AT_FDCWD = -100
const S_IFDIR = 16384 const S_IFDIR = 16384
const S_IFMT = 61440 const S_IFMT = 61440
const PROT_NONE = 0
const PROT_READ = 1 const PROT_READ = 1
const PROT_WRITE = 2 const PROT_WRITE = 2
const PROT_EXEC = 4
const MAP_FAILED = -1
const MAP_SHARED = 1
const MAP_PRIVATE = 2 const MAP_PRIVATE = 2
const MAP_FIXED = 16
const MAP_ANONYMOUS = 32 const MAP_ANONYMOUS = 32
const O_RDONLY = 0 const O_RDONLY = 0

View File

@@ -1,5 +1,5 @@
include "std/num.zr" include "num.zr"
include "std/mem.zr" include "mem.zr"
func u8.is_whitespace[x: u8] : bool func u8.is_whitespace[x: u8] : bool
return x == ' ' || x == '\n' || x == '\t' || x == '\r' return x == ' ' || x == '\n' || x == '\t' || x == '\r'
@@ -29,7 +29,7 @@ func u8.to_str[c: u8] : str
return s return s
func str.free[s: str] : void func str.free[s: str] : void
mem.free(s) (s as ptr)->free()
func str.len[s: str] : i64 func str.len[s: str] : i64
i := 0 i := 0
@@ -103,8 +103,8 @@ func str.format_into[..] : i64
n += 1 n += 1
i += 1 i += 1
else if s[0] == 'f' else if s[0] == 'f'
// TODO: fix when we implement f64 params // TODO: use arrow when we implement f64 params
f64.to_str_buf(_var_arg(i), tmp as ptr) f64.to_str_buf(_var_arg(i) as i64, tmp as ptr)
tmp_len := tmp->len() tmp_len := tmp->len()
remaining := size - n - 1 remaining := size - n - 1
mem.copy(tmp as ptr, buf + n, math.min(tmp_len, remaining)) mem.copy(tmp as ptr, buf + n, math.min(tmp_len, remaining))
@@ -166,7 +166,7 @@ func str.find[haystack: str, needle: str] : i64
return i return i
return -1 return -1
func str.substr[s: str, start: i64, length: i64] : str func str.substr_n[s: str, start: i64, length: i64] : str
out := mem.alloc(length + 1) as str out := mem.alloc(length + 1) as str
mem.copy(s as ptr + start, out as ptr, length) mem.copy(s as ptr + start, out as ptr, length)
out[length] = 0 out[length] = 0
@@ -188,7 +188,7 @@ func str.trim[s: str] : str
while end >= start && s[end]->is_whitespace() while end >= start && s[end]->is_whitespace()
end -= 1 end -= 1
return s->substr(start, end - start + 1) return s->substr_n(start, end - start + 1)
func str.reverse[s: str] : str func str.reverse[s: str] : str
len := s->len() len := s->len()
@@ -233,7 +233,7 @@ func str.hex_encode[s: str, s_len: i64] : str
func str._hex_digit_to_int[d: u8] : u8 func str._hex_digit_to_int[d: u8] : u8
if d->is_digit() if d->is_digit()
return d - '0' return d - '0'
lower : u8 = d | 32 lower := d | 32
if lower >= 'a' && lower <= 'f' if lower >= 'a' && lower <= 'f'
return lower - 'a' + 10 return lower - 'a' + 10
panic("invalid hex digit passed to str._hex_digit_to_int") panic("invalid hex digit passed to str._hex_digit_to_int")
@@ -286,19 +286,14 @@ func str.Builder.build[b: str.Builder] : str
s[b->size] = 0 s[b->size] = 0
return s return s
func str.Builder.destroy[b: str.Builder] : void func str.Builder.build_and_free_buffer[b: str.Builder] : str
s := b->build()
b->free_buffer()
return s
func str.Builder.free_buffer[b: str.Builder] : void
if b->data != 0 if b->data != 0
b->data->free() b->data->free()
b->size = 0 b->size = 0
b->capacity = 0 b->capacity = 0
// here to prevent num depending on mem
func i64.to_str[n: i64] : str
out := mem.alloc(21)
n->to_str_buf(out)
return out as str
func i64.to_hex_str[n: i64] : str
out := mem.alloc(17)
n->to_hex_str_buf(out)
return out as str

33
test.zr
View File

@@ -1,14 +1,14 @@
include "std/io.zr" include "$/io.zr"
include "std/os.zr" include "$/os.zr"
struct TestRunner struct TestRunner
build_blacklist: Array build_blacklist: Array<str>
run_blacklist: Array run_blacklist: Array<str>
custom_build_flags: HashMap custom_build_flags: HashMap<str>
custom_run_args: HashMap custom_run_args: HashMap<str>
func TestRunner.run_directory[tr: TestRunner, dir: str] : void func TestRunner.run_directory[tr: TestRunner, dir: str] : void
~files, ok := os.list_directory(dir) files, ok := os.list_directory(dir)
if !ok if !ok
panic("failed to open test directory") panic("failed to open test directory")
for i in 0..files->size for i in 0..files->size
@@ -28,12 +28,12 @@ func TestRunner.run_test[tr: TestRunner, x: str] : void
io.printf("Building %s...\n", x) io.printf("Building %s...\n", x)
build_cmd := "./target/release/zern "->concat(x) build_cmd := "./target/release/zern "->concat(x)
~custom_build_flags, ok := tr->custom_build_flags->get(name) custom_build_flags, ok := tr->custom_build_flags->get(name)
if ok if ok
build_cmd = build_cmd->concat(" ")->concat(custom_build_flags) build_cmd = build_cmd->concat(" ")->concat(custom_build_flags)
build_start_time := os.time() build_start_time := os.time()
~status, ok := os.run_shell_command(build_cmd) status, ok := os.run_shell_command(build_cmd)
if !ok || status != 0 if !ok || status != 0
os.exit(1) os.exit(1)
build_end_time := os.time() build_end_time := os.time()
@@ -47,12 +47,12 @@ func TestRunner.run_test[tr: TestRunner, x: str] : void
io.printf("Running %s...\n", x) io.printf("Running %s...\n", x)
run_cmd := "./out" run_cmd := "./out"
~custom_run_args, ok := tr->custom_run_args->get(name) custom_run_args, ok := tr->custom_run_args->get(name)
if ok if ok
run_cmd = run_cmd->concat(" ")->concat(custom_run_args) run_cmd = run_cmd->concat(" ")->concat(custom_run_args)
run_start_time := os.time() run_start_time := os.time()
~status, ok := os.run_shell_command(run_cmd) status, ok := os.run_shell_command(run_cmd)
if !ok || status != 0 if !ok || status != 0
io.println("Test failed.") io.println("Test failed.")
os.exit(1) os.exit(1)
@@ -61,18 +61,19 @@ func TestRunner.run_test[tr: TestRunner, x: str] : void
io.printf("Running %s took %dms\n", x, run_end_time - run_start_time) io.printf("Running %s took %dms\n", x, run_end_time - run_start_time)
func main[] : i64 func main[] : i64
~status, ok := os.run_shell_command("cargo build --release") status, ok := os.run_shell_command("cargo build --release")
if !ok || status != 0 if !ok || status != 0
os.exit(1) os.exit(1)
tr := new TestRunner tr := new TestRunner
tr->build_blacklist = [] tr->build_blacklist = [] as Array<str>
tr->run_blacklist = ["raylib.zr", "sqlite_todo.zr", "guess_number.zr", "udp_server.zr", "chip8.zr", "tcp_server.zr"] tr->run_blacklist = ["raylib.zr", "sqlite_todo.zr", "guess_number.zr", "udp_server.zr", "chip8.zr", "serve.zr"]
tr->custom_build_flags = HashMap.new() tr->custom_build_flags = HashMap.new() as HashMap<str>
tr->custom_build_flags->insert("raylib.zr", "-m -C \"-lraylib\"") tr->custom_build_flags->insert("raylib.zr", "-m -C \"-lraylib\"")
tr->custom_build_flags->insert("chip8.zr", "-m -C \"-lraylib\"") tr->custom_build_flags->insert("chip8.zr", "-m -C \"-lraylib\"")
tr->custom_build_flags->insert("sqlite_todo.zr", "-m -C \"-lsqlite3\"") tr->custom_build_flags->insert("sqlite_todo.zr", "-m -C \"-lsqlite3\"")
tr->custom_run_args = HashMap.new() tr->custom_build_flags->insert("serve.zr", "-m -C \"-lpthread\"")
tr->custom_run_args = HashMap.new() as HashMap<str>
tr->custom_run_args->insert("curl.zr", "http://example.com") tr->custom_run_args->insert("curl.zr", "http://example.com")
tr->run_directory("examples") tr->run_directory("examples")