type inference for variables

This commit is contained in:
2026-05-13 14:01:44 +02:00
parent 5f2082ef57
commit 027245684d
37 changed files with 304 additions and 302 deletions

View File

@@ -5,19 +5,19 @@ A very cool language
## Features
* Clean indentation-based syntax
* Compiles to x86_64 Assembly
* Growing [standard library](https://github.com/antpiasecki/zern/tree/main/src/std)
* Growing [standard library](https://git.ton1.dev/toni/zern/src/branch/main/src/std)
* Produces tiny static executables (11KB for `hello.zr`)
* No libc required!
* Has the pipe operator, variadics, dynamic arrays, hashmaps, DNS resolver, etc.
* Has type inference, pipe operator, variadics, dynamic arrays, hashmaps, DNS resolver, etc.
## Syntax
```rust
func main[] : i64
let answer: i64 = math.abs(os.urandom_i64()) % 100
let answer = math.abs(os.urandom_i64()) % 100
while true
io.println("Guess a number: ")
let guess: i64 = io.read_line() |> str.trim() |> str.parse_i64()
let guess = io.read_line() |> str.trim() |> str.parse_i64()
if guess == answer
io.println("You win!")
@@ -44,6 +44,6 @@ func main[] : i64
## Quickstart
```
cargo install --git https://github.com/antpiasecki/zern
cargo install --git https://git.ton1.dev/toni/zern
zern -r hello.zr
```

View File

@@ -1,15 +1,15 @@
func main[] : i64
// https://brainfuck.org/sierpinski.b
let src: str = "++++++++[>+>++++<<-]>++>>+<[-[>>+<<-]+>>]>+[-<<<[->[+[-]+>++>>>-<<]<[<]>>++++++[<<+++++>>-]+<<++.[-]<<]>.>+[>>]>+]"
let src_len: i64 = str.len(src)
let src = "++++++++[>+>++++<<-]>++>>+<[-[>>+<<-]+>>]>+[-<<<[->[+[-]+>++>>>-<<]<[<]>>++++++[<<+++++>>-]+<<++.[-]<<]>.>+[>>]>+]"
let src_len = str.len(src)
let i = 0
let memory: ptr = mem.alloc(30000)
let memory = mem.alloc(30000)
mem.zero(memory, 30000)
let p = 0
while i < src_len
let op: u8 = src[i]
let op = src[i]
if op == '>'
p = p + 1

View File

@@ -22,7 +22,7 @@ struct CHIP8
keyboard_map: Array
func chip8_create[] : CHIP8
let c: CHIP8 = new CHIP8
let c = new CHIP8
c->memory = mem.alloc(4096)
mem.zero(c->memory, 4096)
c->display = mem.alloc(64*32)
@@ -33,7 +33,7 @@ func chip8_create[] : CHIP8
c->stack = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
c->keyboard = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
let fonts: Array = [0xf0, 0x90, 0x90, 0x90, 0xf0, 0x20, 0x60, 0x20, 0x20, 0x70, 0xf0, 0x10, 0xf0, 0x80, 0xf0, 0xf0, 0x10, 0xf0, 0x10, 0xf0, 0x90, 0x90, 0xf0, 0x10, 0x10, 0xf0, 0x80, 0xf0, 0x10, 0xf0, 0xf0, 0x80, 0xf0, 0x90, 0xf0, 0xf0, 0x10, 0x20, 0x40, 0x40, 0xf0, 0x90, 0xf0, 0x90, 0xf0, 0xf0, 0x90, 0xf0, 0x10, 0xf0, 0xf0, 0x90, 0xf0, 0x90, 0x90, 0xe0, 0x90, 0xe0, 0x90, 0xe0, 0xf0, 0x80, 0x80, 0x80, 0xf0, 0xe0, 0x90, 0x90, 0x90, 0xe0, 0xf0, 0x80, 0xf0, 0x80, 0xf0, 0xf0, 0x80, 0xf0, 0x80, 0x80]
let fonts = [0xf0, 0x90, 0x90, 0x90, 0xf0, 0x20, 0x60, 0x20, 0x20, 0x70, 0xf0, 0x10, 0xf0, 0x80, 0xf0, 0xf0, 0x10, 0xf0, 0x10, 0xf0, 0x90, 0x90, 0xf0, 0x10, 0x10, 0xf0, 0x80, 0xf0, 0x10, 0xf0, 0xf0, 0x80, 0xf0, 0x90, 0xf0, 0xf0, 0x10, 0x20, 0x40, 0x40, 0xf0, 0x90, 0xf0, 0x90, 0xf0, 0xf0, 0x90, 0xf0, 0x10, 0xf0, 0xf0, 0x90, 0xf0, 0x90, 0x90, 0xe0, 0x90, 0xe0, 0x90, 0xe0, 0xf0, 0x80, 0x80, 0x80, 0xf0, 0xe0, 0x90, 0x90, 0x90, 0xe0, 0xf0, 0x80, 0xf0, 0x80, 0xf0, 0xf0, 0x80, 0xf0, 0x80, 0x80]
for i in 0..80
c->memory[i] = array.nth(fonts, i)
mem.free(fonts)
@@ -58,18 +58,18 @@ func chip8_disassemble[c: CHIP8, ins_count: i64] : void
for i in 0..ins_count
io.printf("0x%x: ", c->pc)
let high: i64 = c->memory[c->pc] as i64
let low: i64 = c->memory[c->pc + 1] as i64
let high = c->memory[c->pc] as i64
let low = c->memory[c->pc + 1] as i64
c->pc = c->pc + 2
let ins: i64 = (high << 8) | low
let nnn: i64 = ins & 0x0fff
let kk: i64 = ins & 0x00ff
let n: i64 = ins & 0x000f
let x: i64 = (ins >> 8) & 0x0f
let y: i64 = (ins >> 4) & 0x0f
let ins = (high << 8) | low
let nnn = ins & 0x0fff
let kk = ins & 0x00ff
let n = ins & 0x000f
let x = (ins >> 8) & 0x0f
let y = (ins >> 4) & 0x0f
let op: i64 = (ins >> 12) & 0x0f
let op = (ins >> 12) & 0x0f
if op == 0x0
if nnn == 0x0e0
io.println("CLS")
@@ -154,18 +154,18 @@ func chip8_disassemble[c: CHIP8, ins_count: i64] : void
io.printf("??? (%x)\n", ins)
func chip8_step[c: CHIP8] : void
let high: i64 = c->memory[c->pc] as i64
let low: i64 = c->memory[c->pc + 1] as i64
let high = c->memory[c->pc] as i64
let low = c->memory[c->pc + 1] as i64
c->pc = c->pc + 2
let ins: i64 = (high << 8) | low
let nnn: i64 = ins & 0x0fff
let kk: i64 = ins & 0x00ff
let n: i64 = ins & 0x000f
let x: i64 = (ins >> 8) & 0x0f
let y: i64 = (ins >> 4) & 0x0f
let ins = (high << 8) | low
let nnn = ins & 0x0fff
let kk = ins & 0x00ff
let n = ins & 0x000f
let x = (ins >> 8) & 0x0f
let y = (ins >> 4) & 0x0f
let op: i64 = (ins >> 12) & 0x0f
let op = (ins >> 12) & 0x0f
if op == 0x0
if nnn == 0x0e0
mem.zero(c->display, 64 * 32)
@@ -232,7 +232,7 @@ func chip8_step[c: CHIP8] : void
if (c->memory[c->I + row] & (0x80 >> col)) != 0
let pixel_x: u8 = (c->reg[x] + col) % 64
let pixel_y: u8 = (c->reg[y] + row) % 32
let offset: i64 = pixel_x as i64 + (pixel_y * 64)
let offset = pixel_x as i64 + (pixel_y * 64)
if c->display[offset] == 1
c->reg[0xf] = 1
@@ -248,7 +248,7 @@ func chip8_step[c: CHIP8] : void
if kk == 0x07
c->reg[x] = c->delay_timer
else if kk == 0x0A
let key_pressed: bool = false
let key_pressed = false
while !key_pressed && !WindowShouldClose()
for i in 0..16
if IsKeyDown(array.nth(c->keyboard_map, i))
@@ -274,11 +274,11 @@ func chip8_step[c: CHIP8] : void
c->reg[i] = c->memory[c->I + i]
func main[argc: i64, argv: ptr] : i64
let path: str = 0 as str
let disassemble: bool = false
let path = 0 as str
let disassemble = false
for i in 1..argc
let arg: str = mem.read64(argv + i * 8) as str
let arg = mem.read64(argv + i * 8) as str
if str.equal(arg, "-d")
disassemble = true
else
@@ -288,7 +288,7 @@ func main[argc: i64, argv: ptr] : i64
io.println("Usage: chip8 -d <path>")
return 1
let c: CHIP8 = chip8_create()
let c = chip8_create()
let buffer: io.Buffer = must(io.read_binary_file?(path))

View File

@@ -3,7 +3,7 @@ func main[argc: i64, argv: ptr] : i64
io.println("ERROR: url is missing")
return 1
let url: str = mem.read64(argv + 8) as str
let url = mem.read64(argv + 8) as str
if str.len(url) <= 7
io.println("ERROR: invalid url (Did you forget \"http://\"?)")
@@ -13,16 +13,16 @@ func main[argc: i64, argv: ptr] : i64
io.println("ERROR: only http scheme is supported")
return 1
let url_len: i64 = str.len(url)
let url_len = str.len(url)
let host_start = 7
let i: i64 = host_start
let i = host_start
while i < url_len
if url[i] == '/'
break
i = i + 1
let host: str = str.substr(url, host_start, i - host_start)
let path: str = "/"
let host = str.substr(url, host_start, i - host_start)
let path = "/"
if i < url_len
path = str.substr(url, i, url_len - i)
@@ -31,7 +31,7 @@ func main[argc: i64, argv: ptr] : i64
let s: i64 = must(net.connect?(addr, 80))
// TODO: add string builder to std
let req: str = "GET "
let req = "GET "
req = str.concat(req, path)
req = str.concat(req, " HTTP/1.0\r\nHost: ")
req = str.concat(req, host)
@@ -39,16 +39,16 @@ func main[argc: i64, argv: ptr] : i64
net.send(s, req as ptr, str.len(req))
mem.free(req)
let header_buf: str = mem.alloc(8192) as str
let header_buf = mem.alloc(8192) as str
let header_size = 0
let found: bool = false
let end_index: i64 = -1
let found = false
let end_index = -1
while !found && header_size < 8192
let n: i64 = net.read(s, header_buf as ptr + header_size, 8192 - header_size)
let n = net.read(s, header_buf as ptr + header_size, 8192 - header_size)
if n <= 0
break
let current_size: i64 = header_size + n
let current_size = header_size + n
i = 0
while i <= current_size - 4
if header_buf[i] == '\r' && header_buf[i + 1] == '\n' && header_buf[i + 2] == '\r' && header_buf[i + 3] == '\n'
@@ -62,9 +62,9 @@ func main[argc: i64, argv: ptr] : i64
io.print_sized(header_buf as ptr + end_index, header_size as i64 - end_index)
mem.free(header_buf)
let buffer: ptr = mem.alloc(4096)
let buffer = mem.alloc(4096)
while true
let n: i64 = net.read(s, buffer, 4096)
let n = net.read(s, buffer, 4096)
if n <= 0
break
io.print_sized(buffer, n)

View File

@@ -4,6 +4,6 @@ func main[] : i64
while a < 100000
io.println_i64(a)
let temp: i64 = b
let temp = b
b = a + b
a = temp

View File

@@ -1,9 +1,9 @@
func main[] : i64
let answer: i64 = math.abs(os.urandom_i64()) % 100
let answer = math.abs(os.urandom_i64()) % 100
while true
io.println("Guess a number: ")
let guess: i64 = io.read_line() |> str.trim() |> str.parse_i64()
let guess = io.read_line() |> str.trim() |> str.parse_i64()
if guess == answer
io.println("You win!")

View File

@@ -17,13 +17,13 @@ func part2[l1: Array, l2: Array] : void
func main[] : i64
let lines: Array = must(io.read_text_file?("input.txt")) |> str.split("\n")
let l1: Array = []
let l2: Array = []
let l1 = []
let l2 = []
for i in 0..lines->size
let line: str = array.nth(lines, i)
let parts: Array = str.split(line, " ")
let parts = str.split(line, " ")
array.push(l1, str.parse_i64(array.nth(parts, 0)))
array.push(l2, str.parse_i64(array.nth(parts, 1)))

View File

@@ -1,5 +1,5 @@
func check[report: Array] : bool
let increasing: bool = array.nth(report, 0) < array.nth(report, 1)
let increasing = array.nth(report, 0) < array.nth(report, 1)
for i in 0..report->size-1
if array.nth(report, i) > array.nth(report, i + 1) && increasing
@@ -7,7 +7,7 @@ func check[report: Array] : bool
if array.nth(report, i) < array.nth(report, i + 1) && !increasing
return false
let diff: i64 = math.abs(array.nth(report, i) - array.nth(report, i + 1))
let diff = math.abs(array.nth(report, i) - array.nth(report, i + 1))
if diff < 1 || diff > 3
return false
@@ -31,7 +31,7 @@ func part2[data: Array] : void
else
let arr: Array = array.nth(data, i)
for j in 0..arr->size
let sliced: Array = array.concat(array.slice(arr, 0, j), array.slice(arr, j + 1, arr->size - (j + 1)))
let sliced = array.concat(array.slice(arr, 0, j), array.slice(arr, j + 1, arr->size - (j + 1)))
if check(sliced)
out = out + 1
@@ -40,13 +40,13 @@ func part2[data: Array] : void
io.println_i64(out)
func main[] : i64
let lines: Array = must(io.read_text_file?("input.txt")) |> str.split("\n")
let lines = must(io.read_text_file?("input.txt")) |> str.split("\n")
let data: Array = []
let data = []
for i in 0..lines->size
let line: str = array.nth(lines, i)
let report: Array = str.split(line, " ")
let report = str.split(line, " ")
for i in 0..report->size
array.set(report, i, str.parse_i64(array.nth(report, i)))
array.push(data, report)

View File

@@ -43,7 +43,7 @@ func part2[lines: Array] : void
for x in 1..lines->size-1
for y in 1..str.len(array.nth(lines, x))-1
if array.nth(lines, x)[y] == 'A'
let s: str = mem.alloc(5) as str
let s = mem.alloc(5) as str
s[0] = array.nth(lines, x - 1)[y - 1]
s[1] = array.nth(lines, x + 1)[y - 1]
s[2] = array.nth(lines, x + 1)[y + 1]

View File

@@ -12,7 +12,7 @@ func check[update: Array, rules_left: Array, rules_right: Array] : bool
return true
func sort_by_rules[update: Array, rules_left: Array, rules_right: Array] : void
let swapped: bool = true
let swapped = true
while swapped
swapped = false
@@ -20,7 +20,7 @@ func sort_by_rules[update: Array, rules_left: Array, rules_right: Array] : void
let a: i64 = array.nth(update, i)
let b: i64 = array.nth(update, i+1)
if rule_exists(rules_left, rules_right, b, a)
let tmp: i64 = a
let tmp = a
array.set(update, i, b)
array.set(update, i+1, tmp)
swapped = true
@@ -47,23 +47,23 @@ func part2[updates: Array, rules_left: Array, rules_right: Array] : void
io.println_i64(out)
func main[] : i64
let data: Array = must(io.read_text_file?("input.txt")) |> str.split("\n\n")
let data = must(io.read_text_file?("input.txt")) |> str.split("\n\n")
let rules_left: Array = []
let rules_right: Array = []
let rules_lines: Array = str.split(array.nth(data, 0), "\n")
let rules_left = []
let rules_right = []
let rules_lines = str.split(array.nth(data, 0), "\n")
for i in 0..rules_lines->size
let line: str = array.nth(rules_lines, i)
let parts: Array = str.split(line, "|")
let parts = str.split(line, "|")
array.push(rules_left, str.parse_i64(array.nth(parts, 0)))
array.push(rules_right, str.parse_i64(array.nth(parts, 1)))
let updates: Array = []
let updates_lines: Array = str.split(array.nth(data, 1), "\n")
let updates = []
let updates_lines = str.split(array.nth(data, 1), "\n")
for i in 0..updates_lines->size
let line: str = array.nth(updates_lines, i)
let xs: Array = str.split(line, ",")
let xs = str.split(line, ",")
for i in 0..xs->size
array.set(xs, i, str.parse_i64(array.nth(xs, i)))

View File

@@ -1,8 +1,8 @@
func concat[a: i64, b: i64] : i64
let a_str: str = str.from_i64(a)
let b_str: str = str.from_i64(b)
let ab_str: str = str.concat(a_str, b_str)
let out: i64 = str.parse_i64(ab_str)
let a_str = str.from_i64(a)
let b_str = str.from_i64(b)
let ab_str = str.concat(a_str, b_str)
let out = str.parse_i64(ab_str)
// without freeing the program works but leaks 2GB of memory :p
mem.free(a_str)
mem.free(b_str)
@@ -11,8 +11,8 @@ func concat[a: i64, b: i64] : i64
func solve[ops: Array, e: Array] : i64
let e_1: Array = array.nth(e, 1)
let n: i64 = e_1->size - 1
let indices: Array = []
let n = e_1->size - 1
let indices = []
for i in 0..n
array.push(indices, 0)
@@ -30,8 +30,8 @@ func solve[ops: Array, e: Array] : i64
if res == array.nth(e, 0)
return res
let done: bool = true
let i: i64 = n - 1
let done = true
let i = n - 1
while i >= 0
array.set(indices, i, array.nth(indices, i) + 1)
@@ -61,14 +61,14 @@ func part2[equations: Array] : void
io.println_i64(out)
func main[] : i64
let lines: Array = must(io.read_text_file?("input.txt")) |> str.split("\n")
let equations: Array = []
let lines = must(io.read_text_file?("input.txt")) |> str.split("\n")
let equations = []
for i in 0..lines->size
let line: str = array.nth(lines, i)
let parts: Array = str.split(line, ": ")
let parts = str.split(line, ": ")
let xs: Array = str.split(array.nth(parts, 1), " ")
let xs = str.split(array.nth(parts, 1), " ")
for j in 0..xs->size
array.set(xs, j, str.parse_i64(array.nth(xs, j)))

View File

@@ -4,8 +4,8 @@ func part1[lines: Array] : void
for i in 0..lines->size
let line: str = array.nth(lines, i)
let dir: u8 = line[0]
let n: i64 = str.substr(line, 1, str.len(line) - 1) |> str.parse_i64()
let dir = line[0]
let n = str.substr(line, 1, str.len(line) - 1) |> str.parse_i64()
if dir == 'L'
dial = dial - n
@@ -27,8 +27,8 @@ func part2[lines: Array] : void
for i in 0..lines->size
let line: str = array.nth(lines, i)
let dir: u8 = line[0]
let n: i64 = str.substr(line, 1, str.len(line) - 1) |> str.parse_i64()
let dir = line[0]
let n = str.substr(line, 1, str.len(line) - 1) |> str.parse_i64()
if dir == 'L'
for i in 0..n
@@ -47,7 +47,7 @@ func part2[lines: Array] : void
io.println_i64(password)
func main[] : i64
let lines: Array = must(io.read_text_file?("input.txt")) |> str.split("\n")
let lines = must(io.read_text_file?("input.txt")) |> str.split("\n")
part1(lines)
part2(lines)

View File

@@ -1,10 +1,10 @@
func part1_is_invalid_id[s: str] : bool
let len: i64 = str.len(s)
let len = str.len(s)
if len % 2 != 0
return false
let first: str = str.substr(s, 0, len / 2)
let second: str = str.substr(s, len / 2, len / 2)
let first = str.substr(s, 0, len / 2)
let second = str.substr(s, len / 2, len / 2)
return str.equal(first, second)
@@ -12,9 +12,9 @@ func part1[ranges: Array] : void
let sum = 0
for i in 0..ranges->size
let parts: Array = array.nth(ranges, i) |> str.split("-")
let start: i64 = array.nth(parts, 0) |> str.parse_i64()
let end: i64 = array.nth(parts, 1) |> str.parse_i64()
let parts = array.nth(ranges, i) |> str.split("-")
let start = array.nth(parts, 0) |> str.parse_i64()
let end = array.nth(parts, 1) |> str.parse_i64()
for n in (start)..end+1
if part1_is_invalid_id(str.from_i64(n))
@@ -24,15 +24,15 @@ func part1[ranges: Array] : void
// had to cheat this one
func part2_is_invalid_id[s: str] : bool
let len: i64 = str.len(s)
let len = str.len(s)
if len < 2
return false
for div in 1..(len / 2 + 1)
if len % div == 0
let u: str = str.substr(s, 0, div)
let is_repeat: bool = true
let u = str.substr(s, 0, div)
let is_repeat = true
for k in 1..(len / div)
let segment: str = str.substr(s, k * div, div)
let segment = str.substr(s, k * div, div)
if !str.equal(segment, u)
is_repeat = false
if is_repeat
@@ -43,9 +43,9 @@ func part2[ranges: Array] : void
let sum = 0
for i in 0..ranges->size
let parts: Array = array.nth(ranges, i) |> str.split("-")
let start: i64 = array.nth(parts, 0) |> str.parse_i64()
let end: i64 = array.nth(parts, 1) |> str.parse_i64()
let parts = array.nth(ranges, i) |> str.split("-")
let start = array.nth(parts, 0) |> str.parse_i64()
let end = array.nth(parts, 1) |> str.parse_i64()
for n in (start)..end+1
if part2_is_invalid_id(str.from_i64(n))
@@ -54,7 +54,7 @@ func part2[ranges: Array] : void
io.println_i64(sum)
func main[] : i64
let ranges: Array = must(io.read_text_file?("input.txt")) |> str.split(",")
let ranges = must(io.read_text_file?("input.txt")) |> str.split(",")
part1(ranges)
part2(ranges)

View File

@@ -7,11 +7,11 @@ func part1[lines: Array] : void
let largest = 0
for j in 0..str.len(line)
for k in (j+1)..str.len(line)
let s: str = mem.alloc(3) as str
let s = mem.alloc(3) as str
s[0] = line[j]
s[1] = line[k]
s[2] = 0
let n: i64 = str.parse_i64(s)
let n = str.parse_i64(s)
if n > largest
largest = n
@@ -21,11 +21,11 @@ func part1[lines: Array] : void
// had to cheat this one
func part2_rec[bank: str, start: i64, remaining: i64] : i64
let largest = 0
let largest_idx: i64 = start
let len: i64 = str.len(bank)
let largest_idx = start
let len = str.len(bank)
for i in (start)..(len-remaining+1)
let v: i64 = (bank[i] - '0') as i64
let v = (bank[i] - '0') as i64
if v > largest
largest = v
largest_idx = i
@@ -45,7 +45,7 @@ func part2[lines: Array] : void
io.println_i64(sum)
func main[] : i64
let lines: Array = must(io.read_text_file?("input.txt")) |> str.split("\n")
let lines = must(io.read_text_file?("input.txt")) |> str.split("\n")
part1(lines)
part2(lines)

View File

@@ -6,7 +6,7 @@ func main[] : i64
while a < 4000000
if a % 2 == 0
sum = sum + a
let temp: i64 = b
let temp = b
b = a + b
a = temp

View File

@@ -4,8 +4,8 @@ func main[] : i64
for a in 500..1000
for b in 500..1000
if a * b > out
let s: str = str.from_i64(a * b)
let s_rev: str = str.reverse(s)
let s = str.from_i64(a * b)
let s_rev = str.reverse(s)
if str.equal(s, s_rev)
out = a * b
mem.free(s)

View File

@@ -1,8 +1,8 @@
func main[] : i64
let n: str = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450"
let n = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450"
let out = 0
let max: i64 = str.len(n) - 13
let max = str.len(n) - 13
for i in 0..max
let s = 1
let j = 0

View File

@@ -1,7 +1,7 @@
func main[] : i64
for a in 1..1000
for b in 1..1000
let c: i64 = 1000 - b - a
let c = 1000 - b - a
if a * a + b * b == c * c
io.println_i64(a * b * c)
return 0

View File

@@ -1,7 +1,7 @@
func main[] : i64
let N = 20
let grid: Array = []
let grid = []
array.push(grid, [8, 2, 22, 97, 38, 15, 0, 40, 0, 75, 4, 5, 7, 78, 52, 12, 50, 77, 91, 8])
array.push(grid, [49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 4, 56, 62, 0])
array.push(grid, [81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 3, 49, 13, 36, 65])

View File

@@ -1,5 +1,5 @@
func num_divisors[n: i64] : i64
let end: i64 = math.isqrt(n)
let end = math.isqrt(n)
let out = 0
for i in 1..end+1

View File

@@ -15,7 +15,7 @@ func main[] : i64
let max_index = 0
for i in 1..1000000
let seq: i64 = collatz_seq(i)
let seq = collatz_seq(i)
if seq > max
max = seq
max_index = i

View File

@@ -1,5 +1,5 @@
func main[] : i64
let n: Array = []
let n = []
array.push(n, 1)
for j in 0..1000

View File

@@ -1,7 +1,7 @@
func main[] : i64
let s1: Array = [0, 3, 3, 5, 4, 4, 3, 5, 5, 4]
let s2: Array = [3, 6, 6, 8, 8, 7, 7, 9, 8, 8]
let s3: Array = [0, 0, 6, 6, 5, 5, 5, 7, 6, 6]
let s1 = [0, 3, 3, 5, 4, 4, 3, 5, 5, 4]
let s2 = [3, 6, 6, 8, 8, 7, 7, 9, 8, 8]
let s3 = [0, 0, 6, 6, 5, 5, 5, 7, 6, 6]
let sum = 0

View File

@@ -2,13 +2,13 @@ func findmax[triangle: Array, row: i64, col: i64] : i64
if row == 14
return array.nth(array.nth(triangle, row), col)
let left: i64 = findmax(triangle, row + 1, col)
let right: i64 = findmax(triangle, row + 1, col + 1)
let left = findmax(triangle, row + 1, col)
let right = findmax(triangle, row + 1, col + 1)
return array.nth(array.nth(triangle, row), col) + math.max(left, right)
func main[] : i64
let triangle: Array = []
let triangle = []
array.push(triangle, [75])
array.push(triangle, [95, 64])
array.push(triangle, [17, 47, 82])

View File

@@ -9,7 +9,7 @@ func multiply[n: Array, x: i64] : void
carry = carry / 10
func main[] : i64
let n: Array = [1]
let n = [1]
for i in 2..101
multiply(n, i)

View File

@@ -1,5 +1,5 @@
func divisors_sum[n: i64] : i64
let k: i64 = n
let k = n
let sum = 1
for i in 2..k+1
@@ -14,7 +14,7 @@ func main[] : i64
let sum = 0
for i in 2..10000
let d: i64 = divisors_sum(i)
let d = divisors_sum(i)
if i < d && i == divisors_sum(d)
sum = sum + i + d

View File

@@ -1,5 +1,5 @@
func main[] : i64
let arr: Array = []
let arr = []
for i in 0..10
array.push(arr, math.abs(os.urandom_i64()) % 1000)

View File

@@ -1,12 +1,12 @@
func rule110_step[state: Array] : Array
let new_state: Array = []
let new_state = []
for i in 0..state->size
let left: bool = false
let left = false
if i - 1 >= 0
left = array.nth(state, i - 1)
let center: bool = array.nth(state, i)
let right: bool = false
let right = false
if i + 1 < state->size
right = array.nth(state, i + 1)
@@ -25,7 +25,7 @@ func print_state[state: Array]: void
func main[] : i64
let SIZE = 60
let state: Array = []
let state = []
for i in 0..SIZE
array.push(state, false)
array.push(state, true)

View File

@@ -30,7 +30,7 @@ func main[] : i64
io.println("0. Quit")
io.print("\n> ")
let choice: i64 = io.read_line() |> str.parse_i64()
let choice = io.read_line() |> str.parse_i64()
if choice == 0
break
@@ -39,8 +39,8 @@ func main[] : i64
sqlite3_prepare_v2(db, "SELECT * FROM todo", -1, ^stmt, 0)
while sqlite3_step(stmt) == 100
let id: i64 = sqlite3_column_int(stmt, 0)
let task: str = sqlite3_column_text(stmt, 1)
let id = sqlite3_column_int(stmt, 0)
let task = sqlite3_column_text(stmt, 1)
io.print_i64(id)
io.print(" - ")
@@ -49,7 +49,7 @@ func main[] : i64
io.println("============")
else if choice == 2
io.print("\nEnter new task: ")
let task: str = io.read_line() |> str.trim()
let task = io.read_line() |> str.trim()
sqlite3_prepare_v2(db, "INSERT INTO todo(task) VALUES (?);", -1, ^stmt, 0)
sqlite3_bind_text(stmt, 1, task, -1, 0)
@@ -59,7 +59,7 @@ func main[] : i64
io.println("\nTask added\n")
else if choice == 3
io.print("\nEnter task id: ")
let id: i64 = io.read_line() |> str.parse_i64()
let id = io.read_line() |> str.parse_i64()
sqlite3_prepare_v2(db, "DELETE FROM todo WHERE id = ?;", -1, ^stmt, 0)
sqlite3_bind_int(stmt, 1, id, -1, 0)

View File

@@ -2,12 +2,12 @@ func main[] : i64
let s: i64 = must(net.listen?(net.pack_addr(127, 0, 0, 1), 8000))
io.println("Listening on port 8000...")
let resp: ptr = mem.alloc(60000)
let resp = mem.alloc(60000)
while true
let conn: i64 = net.accept(s)
let conn = net.accept(s)
if conn < 0
continue
let n: i64 = net.read(conn, resp, 60000)
let n = net.read(conn, resp, 60000)
net.send(conn, resp, n)
net.close(conn)

View File

@@ -3,7 +3,7 @@ func main[] : i64
io.println("Listening on port 8000...")
while true
let pkt: net.UDPPacket = net.udp_receive(s, 60000)
let pkt = net.udp_receive(s, 60000)
if pkt->size <= 0
net.UDPPacket.free(pkt)
continue

View File

@@ -75,16 +75,21 @@ pub struct CodegenX86_64<'a> {
label_counter: usize,
data_counter: usize,
pub symbol_table: &'a SymbolTable,
pub expr_types: &'a HashMap<usize, String>,
}
impl<'a> CodegenX86_64<'a> {
pub fn new(symbol_table: &'a SymbolTable) -> CodegenX86_64<'a> {
pub fn new(
symbol_table: &'a SymbolTable,
expr_types: &'a HashMap<usize, String>,
) -> CodegenX86_64<'a> {
CodegenX86_64 {
output: String::new(),
data_section: String::new(),
label_counter: 0,
data_counter: 1,
symbol_table,
expr_types,
}
}
@@ -218,11 +223,9 @@ _builtin_environ:
let var_type: String = match var_type {
Some(t) => t.lexeme.clone(),
None => match &initializer.kind {
ExprKind::Literal(token) if token.token_type == TokenType::IntLiteral => {
"i64".into()
}
_ => return error!(&name.loc, "unable to infer variable type"),
None => match self.expr_types[&initializer.id].as_str() {
"any" => return error!(name.loc, "cannot infer type from any"),
t => t.into(),
},
};
@@ -557,10 +560,8 @@ _builtin_environ:
self.symbol_table.constants[&name.lexeme]
);
} else {
let var = match env.get_var(&name.lexeme) {
Some(x) => x,
None => unreachable!("this should be caught in the typechecker"),
};
// already ensured by the typechecker
let var = env.get_var(&name.lexeme).unwrap();
emit!(
&mut self.output,
" mov rax, QWORD [rbp-{}]",
@@ -573,10 +574,8 @@ _builtin_environ:
match &left.kind {
ExprKind::Variable(name) => {
let var = match env.get_var(&name.lexeme) {
Some(x) => x,
None => unreachable!(),
};
// already ensured by the typechecker
let var = env.get_var(&name.lexeme).unwrap();
emit!(
&mut self.output,
" mov QWORD [rbp-{}], rax",

View File

@@ -54,7 +54,7 @@ fn compile_file(args: Args) -> Result<(), ZernError> {
typechecker.typecheck_stmt(&mut typechecker::Env::new(), stmt)?;
}
let mut codegen = codegen_x86_64::CodegenX86_64::new(&symbol_table);
let mut codegen = codegen_x86_64::CodegenX86_64::new(&symbol_table, &typechecker.expr_types);
codegen.emit_prologue(args.use_crt)?;
for stmt in statements {
codegen.compile_stmt(&mut codegen_x86_64::Env::new(), &stmt)?;

View File

@@ -6,7 +6,7 @@ const SO_REUSEADDR = 2
func net.listen?[packed_host: i64, port: i64] : i64
err.clear()
let s: i64 = _builtin_syscall(SYS_socket, AF_INET, SOCK_STREAM, 0)
let s = _builtin_syscall(SYS_socket, AF_INET, SOCK_STREAM, 0)
if s < 0
err.set(ERR_SYSCALL_FAILED, "net.listen?: failed to create a socket")
return -1
@@ -17,7 +17,7 @@ func net.listen?[packed_host: i64, port: i64] : i64
err.set(ERR_SYSCALL_FAILED, "net.listen?: setsockopt() failed")
return -1
let sa: ptr = mem.alloc(16)
let sa = mem.alloc(16)
mem.zero(sa, 16)
sa[0] = 2
sa[1] = 0
@@ -44,12 +44,12 @@ func net.listen?[packed_host: i64, port: i64] : i64
func net.connect?[packed_host: i64, port: i64] : i64
err.clear()
let s: i64 = _builtin_syscall(SYS_socket, AF_INET, SOCK_STREAM, 0)
let s = _builtin_syscall(SYS_socket, AF_INET, SOCK_STREAM, 0)
if s < 0
err.set(ERR_SYSCALL_FAILED, "net.connect?: failed to create a socket")
return -1
let sa: ptr = mem.alloc(16)
let sa = mem.alloc(16)
mem.zero(sa, 16)
sa[0] = AF_INET
sa[1] = 0
@@ -95,7 +95,7 @@ struct net.UDPPacket
func net.create_udp_client?[packed_host: i64, port: i64] : net.UDPSocket
err.clear()
let s: net.UDPSocket = new net.UDPSocket
let s = new net.UDPSocket
s->fd = _builtin_syscall(SYS_socket, AF_INET, SOCK_DGRAM, 0)
if s->fd < 0
@@ -117,7 +117,7 @@ func net.create_udp_client?[packed_host: i64, port: i64] : net.UDPSocket
func net.create_udp_server?[packed_host: i64, port: i64] : net.UDPSocket
err.clear()
let s: net.UDPSocket = net.create_udp_client?(packed_host, port)
let s = net.create_udp_client?(packed_host, port)
if err.check()
return 0 as net.UDPSocket
@@ -132,7 +132,7 @@ func net.udp_send_to[s: net.UDPSocket, addr: ptr, data: ptr, size: i64] : void
_builtin_syscall(SYS_sendto, s->fd, data, size, 0, addr, 16)
func net.udp_receive[s: net.UDPSocket, size: i64] : net.UDPPacket
let pkt: net.UDPPacket = new net.UDPPacket
let pkt = new net.UDPPacket
pkt->data = mem.alloc(size)
pkt->source_addr = mem.alloc(16)
mem.zero(pkt->source_addr, 16)
@@ -156,14 +156,14 @@ const DNS_CLASS_IN = 1
const DNS_RECURSION_DESIRED = 256
func net.encode_dns_name[domain: str] : io.Buffer
let domain_len: i64 = str.len(domain)
let domain_len = str.len(domain)
let buf: io.Buffer = must(io.Buffer.alloc?(domain_len + 2))
let out_pos = 0
let part_start = 0
let i = 0
while i <= domain_len
if i == domain_len || domain[i] == '.'
let part_len: i64 = i - part_start
let part_len = i - part_start
buf->data[out_pos] = part_len & 0xff
out_pos = out_pos + 1
mem.copy(domain as ptr + part_start, buf->data + out_pos, part_len)
@@ -175,11 +175,11 @@ func net.encode_dns_name[domain: str] : io.Buffer
return buf
func net.build_dns_query[domain_name: str, record_type: i64] : io.Buffer
let name: io.Buffer = net.encode_dns_name(domain_name)
let name = net.encode_dns_name(domain_name)
let out: io.Buffer = must(io.Buffer.alloc?(12 + name->size + 4))
// header
let id: i64 = math.abs(os.urandom_i64() % 65536)
let id = math.abs(os.urandom_i64() % 65536)
mem.write16be(out->data + 0, id)
mem.write16be(out->data + 2, DNS_RECURSION_DESIRED)
mem.write16be(out->data + 4, 1) // num_questions
@@ -198,16 +198,16 @@ func net.build_dns_query[domain_name: str, record_type: i64] : io.Buffer
// TODO: dont resolve IPs
func net.resolve?[domain: str] : i64
err.clear()
let query: io.Buffer = net.build_dns_query(domain, DNS_TYPE_A)
let query = net.build_dns_query(domain, DNS_TYPE_A)
// TODO: this probably shouldnt be hardcoded
let s: net.UDPSocket = net.create_udp_client?(net.pack_addr(1, 1, 1, 1), 53)
let s = net.create_udp_client?(net.pack_addr(1, 1, 1, 1), 53)
if err.check()
return -1
net.udp_send_to(s, s->addr, query->data, query->size)
io.Buffer.free(query)
let pkt: net.UDPPacket = net.udp_receive(s, 1024)
let pkt = net.udp_receive(s, 1024)
net.UDPSocket.close_and_free(s)
// TODO: do actual parsing
@@ -221,6 +221,6 @@ func net.resolve?[domain: str] : i64
pos = pos + 12 // skip name(2), type(2), class(2), ttl(4), rdlength(2)
let out: i64 = net.pack_addr(pkt->data[pos] as i64, pkt->data[pos+1] as i64, pkt->data[pos+2] as i64, pkt->data[pos+3] as i64)
let out = net.pack_addr(pkt->data[pos] as i64, pkt->data[pos+1] as i64, pkt->data[pos+2] as i64, pkt->data[pos+3] as i64)
net.UDPPacket.free(pkt)
return out

View File

@@ -48,14 +48,14 @@ func mem._align[x: i64] : i64
func mem._split_block[blk: mem.Block, needed: i64] : void
if blk->size >= needed + MEM_BLOCK_SIZE + 8
let new_blk: mem.Block = (blk as ptr + MEM_BLOCK_SIZE + needed) as mem.Block
let new_blk = (blk as ptr + MEM_BLOCK_SIZE + needed) as mem.Block
new_blk->size = blk->size - needed - MEM_BLOCK_SIZE
new_blk->free = true
new_blk->next = blk->next
new_blk->prev = blk
if blk->next as ptr
let next: mem.Block = blk->next
let next = blk->next
next->prev = new_blk
else
mem.write64(_builtin_heap_tail(), new_blk)
@@ -65,25 +65,23 @@ func mem._split_block[blk: mem.Block, needed: i64] : void
func mem._request_space?[size: i64] : mem.Block
err.clear()
let needed: i64 = size + MEM_BLOCK_SIZE
let alloc_size: i64 = (needed + 4095) & -4096
let needed = size + MEM_BLOCK_SIZE
let alloc_size = (needed + 4095) & -4096
// PROT_READ | PROT_WRITE = 3
// MAP_PRIVATE | MAP_ANONYMOUS = 34
// fd = -1, offset = 0
let blk_ptr: ptr = _builtin_syscall(SYS_mmap, 0, alloc_size, 3, 34, -1, 0) as ptr
if blk_ptr == -1
let blk = _builtin_syscall(SYS_mmap, 0, alloc_size, 3, 34, -1, 0) as mem.Block
if (blk as ptr as i64) == -1
err.set(ERR_ALLOC_FAILED, "mem._request_space: mmap failed")
return 0 as mem.Block
let blk: mem.Block = blk_ptr as mem.Block
blk->size = alloc_size - MEM_BLOCK_SIZE
blk->free = false
blk->next = 0 as mem.Block
blk->prev = 0 as mem.Block
let tail: mem.Block = mem.read64(_builtin_heap_tail()) as mem.Block
let tail = mem.read64(_builtin_heap_tail()) as mem.Block
if tail as ptr
tail->next = blk
blk->prev = tail
@@ -99,7 +97,7 @@ func mem.alloc?[size: i64] : ptr
size = mem._align(size)
let cur: mem.Block = mem.read64(_builtin_heap_head()) as mem.Block
let cur = mem.read64(_builtin_heap_head()) as mem.Block
while cur as ptr
if cur->free && cur->size >= size
mem._split_block(cur, size)
@@ -107,7 +105,7 @@ func mem.alloc?[size: i64] : ptr
return cur as ptr + MEM_BLOCK_SIZE
cur = cur->next
let blk: mem.Block = mem._request_space?(size)
let blk = mem._request_space?(size)
if err.check()
return 0 as ptr
@@ -125,43 +123,43 @@ func mem.free[x: any] : void
if !(x as ptr)
return 0
let blk: mem.Block = (x as ptr - MEM_BLOCK_SIZE) as mem.Block
let blk = (x as ptr - MEM_BLOCK_SIZE) as mem.Block
blk->free = true
let next: mem.Block = blk->next
let next = blk->next
if next as ptr && next->free
let expected_next: mem.Block = (blk as ptr + MEM_BLOCK_SIZE + blk->size) as mem.Block
let expected_next = (blk as ptr + MEM_BLOCK_SIZE + blk->size) as mem.Block
if expected_next as ptr == next as ptr
blk->size = blk->size + MEM_BLOCK_SIZE + next->size
blk->next = next->next
if next->next as ptr
let b: mem.Block = next->next
let b = next->next
b->prev = blk
if mem.read64(_builtin_heap_tail()) == next as ptr
mem.write64(_builtin_heap_tail(), blk)
let prev: mem.Block = blk->prev
let prev = blk->prev
if prev as ptr && prev->free
let expected_blk: mem.Block = (prev as ptr + MEM_BLOCK_SIZE + prev->size) as mem.Block
let expected_blk = (prev as ptr + MEM_BLOCK_SIZE + prev->size) as mem.Block
if expected_blk as ptr == blk as ptr
prev->size = prev->size + MEM_BLOCK_SIZE + blk->size
prev->next = blk->next
if blk->next as ptr
let b: mem.Block = blk->next
let b = blk->next
b->prev = prev
if mem.read64(_builtin_heap_tail()) == blk as ptr
mem.write64(_builtin_heap_tail(), prev)
blk = prev
let block_total: i64 = blk->size + MEM_BLOCK_SIZE
let block_total = blk->size + MEM_BLOCK_SIZE
if (blk as i64 & 4095) == 0 && (block_total & 4095) == 0
if blk->prev as ptr
let b: mem.Block = blk->prev
let b = blk->prev
b->next = blk->next
else
mem.write64(_builtin_heap_head(), blk->next)
if blk->next as ptr
let b: mem.Block = blk->next
let b = blk->next
b->prev = blk->prev
else
mem.write64(_builtin_heap_tail(), blk->prev)
@@ -182,28 +180,28 @@ func mem.realloc?[x: ptr, new_size: i64] : ptr
new_size = mem._align(new_size)
let blk: mem.Block = (x - MEM_BLOCK_SIZE) as mem.Block
let blk = (x - MEM_BLOCK_SIZE) as mem.Block
if blk->size >= new_size
mem._split_block(blk, new_size)
return x
let next: mem.Block = blk->next
let expected_next: mem.Block = (blk as ptr + MEM_BLOCK_SIZE + blk->size) as mem.Block
let next = blk->next
let expected_next = (blk as ptr + MEM_BLOCK_SIZE + blk->size) as mem.Block
if next as ptr && next->free && expected_next as ptr == next as ptr
let combined: i64 = blk->size + MEM_BLOCK_SIZE + next->size
let combined = blk->size + MEM_BLOCK_SIZE + next->size
if combined >= new_size
blk->size = combined
blk->next = next->next
if next->next as ptr
let b: mem.Block = next->next
let b = next->next
b->prev = blk
if mem.read64(_builtin_heap_tail()) == next as ptr
mem.write64(_builtin_heap_tail(), blk)
mem._split_block(blk, new_size)
return x
let new_ptr: ptr = mem.alloc?(new_size)
let new_ptr = mem.alloc?(new_size)
if err.check()
return 0 as ptr
@@ -221,7 +219,7 @@ func mem.zero[x: ptr, size: i64] : void
func mem.copy[src: ptr, dst: ptr, n: i64] : void
if dst > src
let i: i64 = n - 1
let i = n - 1
while i >= 0
dst[i] = src[i]
i = i - 1
@@ -265,8 +263,8 @@ func mem.write64[x: ptr, d: any] : void
_builtin_set64(x, d)
func io.printf[..] : void
let s: ptr = _var_arg(0) as ptr
let i: i64 = 1
let s = _var_arg(0) as ptr
let i = 1
while s[0]
if s[0] == '%'
@@ -312,29 +310,29 @@ func io.print_bool[x: bool] : void
io.print("false")
func io.print_i64[x: i64] : void
let s: str = str.from_i64(x)
let s = str.from_i64(x)
io.print(s)
mem.free(s)
func io.print_i64_hex[x: i64] : void
let s: str = str.hex_from_i64(x)
let s = str.hex_from_i64(x)
io.print(s)
mem.free(s)
func io.println_i64[x: i64] : void
let s: str = str.from_i64(x)
let s = str.from_i64(x)
io.println(s)
mem.free(s)
func io.read_char[] : u8
let c: u8 = 0 as u8
let c = 0 as u8
_builtin_syscall(SYS_read, 0, ^c, 1)
return c
func io.read_line[]: str
let MAX_SIZE = 60000
let buffer: str = mem.alloc(MAX_SIZE + 1) as str
let n: i64 = _builtin_syscall(SYS_read, 0, buffer, MAX_SIZE)
let buffer = mem.alloc(MAX_SIZE + 1) as str
let n = _builtin_syscall(SYS_read, 0, buffer, MAX_SIZE)
if n < 0
n = 0
buffer[n] = 0
@@ -347,7 +345,7 @@ struct io.Buffer
func io.Buffer.alloc?[size: i64] : io.Buffer
err.clear()
let buffer: io.Buffer = new io.Buffer
let buffer = new io.Buffer
buffer->size = size
buffer->data = mem.alloc?(size)
if err.check()
@@ -366,9 +364,9 @@ const S_IFDIR = 0o040000
const S_IFMT = 0o170000
func io.is_a_directory[path: str] : bool
let st: ptr = mem.alloc(256) // it has 21 mixed-size fields so `ptr` must do for now
let st = mem.alloc(256) // it has 21 mixed-size fields so no struct for now
let rc: i64 = _builtin_syscall(SYS_newfstatat, -100, path, st, 0)
let rc = _builtin_syscall(SYS_newfstatat, -100, path, st, 0)
if rc != 0
mem.free(st)
return false
@@ -380,20 +378,20 @@ func io.is_a_directory[path: str] : bool
func io.read_text_file?[path: str] : str
err.clear()
let fd: i64 = _builtin_syscall(SYS_openat, -100, path, 0, 0)
let fd = _builtin_syscall(SYS_openat, -100, path, 0, 0)
if fd < 0
err.set(ERR_OPEN_FAILED, "io.read_text_file?: failed to open file")
return 0 as str
let size: i64 = _builtin_syscall(SYS_lseek, fd, 0, 2)
let size = _builtin_syscall(SYS_lseek, fd, 0, 2)
_builtin_syscall(SYS_lseek, fd, 0, 0)
let buffer: str = mem.alloc?(size + 1) as str
let buffer = mem.alloc?(size + 1) as str
if err.check()
_builtin_syscall(SYS_close, fd)
return 0 as str
let n: i64 = _builtin_syscall(SYS_read, fd, buffer, size)
let n = _builtin_syscall(SYS_read, fd, buffer, size)
_builtin_syscall(SYS_close, fd)
if n != size
@@ -406,12 +404,12 @@ func io.read_text_file?[path: str] : str
func io.read_binary_file?[path: str] : io.Buffer
err.clear()
let fd: i64 = _builtin_syscall(SYS_openat, -100, path, 0, 0)
let fd = _builtin_syscall(SYS_openat, -100, path, 0, 0)
if fd < 0
err.set(ERR_OPEN_FAILED, "io.read_binary_file?: failed to open file")
return 0 as io.Buffer
let buf: io.Buffer = new io.Buffer
let buf = new io.Buffer
buf->size = _builtin_syscall(SYS_lseek, fd, 0, 2)
_builtin_syscall(SYS_lseek, fd, 0, 0)
@@ -421,7 +419,7 @@ func io.read_binary_file?[path: str] : io.Buffer
_builtin_syscall(SYS_close, fd)
return 0 as io.Buffer
let n: i64 = _builtin_syscall(SYS_read, fd, buf->data, buf->size)
let n = _builtin_syscall(SYS_read, fd, buf->data, buf->size)
_builtin_syscall(SYS_close, fd)
if n != buf->size
@@ -436,12 +434,12 @@ func io.write_file?[path: str, content: str] : void
func io.write_binary_file?[path: str, content: ptr, size: i64] : void
err.clear()
let fd: i64 = _builtin_syscall(SYS_openat, -100, path, 0x241, 0o644)
let fd = _builtin_syscall(SYS_openat, -100, path, 0x241, 0o644)
if fd < 0
err.set(ERR_OPEN_FAILED, "io.write_binary_file?: failed to open file")
return 0
let n: i64 = _builtin_syscall(SYS_write, fd, content, size)
let n = _builtin_syscall(SYS_write, fd, content, size)
_builtin_syscall(SYS_close, fd)
if n != size
err.set(ERR_WRITE_FAILED, "io.write_binary_file?: failed to write file")
@@ -454,8 +452,8 @@ func str.len[s: str] : i64
return i
func str.make_copy[s: str] : str
let size: i64 = str.len(s) + 1
let dup: str = mem.alloc(size) as str
let size = str.len(s) + 1
let dup = mem.alloc(size) as str
mem.copy(s as ptr, dup as ptr, size)
return dup
@@ -489,9 +487,9 @@ func str.is_alphanumeric[x: u8] : bool
return str.is_letter(x) || str.is_digit(x)
func str.concat[a: str, b: str] : str
let a_len: i64 = str.len(a)
let b_len: i64 = str.len(b)
let out: str = mem.alloc(a_len + b_len + 1) as str
let a_len = str.len(a)
let b_len = str.len(b)
let out = mem.alloc(a_len + b_len + 1) as str
mem.copy(a as ptr, out as ptr, a_len)
mem.copy(b as ptr, out as ptr + a_len, b_len)
out[a_len + b_len] = 0
@@ -501,8 +499,8 @@ func str.contains[haystack: str, needle: str] : bool
return str.find(haystack, needle) != -1
func str.find[haystack: str, needle: str] : i64
let haystack_len: i64 = str.len(haystack)
let needle_len: i64 = str.len(needle)
let haystack_len = str.len(haystack)
let needle_len = str.len(needle)
if needle_len == 0
return 0
@@ -511,7 +509,7 @@ func str.find[haystack: str, needle: str] : i64
return -1
for i in 0..(haystack_len - needle_len + 1)
let match: bool = true
let match = true
for j in 0..needle_len
if haystack[i + j] != needle[j]
match = false
@@ -524,20 +522,20 @@ func str.substr[s: str, start: i64, length: i64] : str
if start < 0 || length < 0 || start + length > str.len(s)
panic("str.substr out of bounds")
let out: str = mem.alloc(length + 1) as str
let out = mem.alloc(length + 1) as str
mem.copy(s as ptr + start, out as ptr, length)
out[length] = 0
return out
func str.trim[s: str] : str
let len: i64 = str.len(s)
let len = str.len(s)
if len == 0
let out: str = mem.alloc(1) as str
let out = mem.alloc(1) as str
out[0] = 0
return out
let start = 0
let end: i64 = len - 1
let end = len - 1
while start <= end && str.is_whitespace(s[start])
start = start + 1
@@ -548,9 +546,9 @@ func str.trim[s: str] : str
return str.substr(s, start, end - start + 1)
func str.split[haystack: str, needle: str]: Array
let haystack_len: i64 = str.len(haystack)
let needle_len: i64 = str.len(needle)
let result: Array = []
let haystack_len = str.len(haystack)
let needle_len = str.len(needle)
let result = []
if !needle_len
if !haystack_len
@@ -564,7 +562,7 @@ func str.split[haystack: str, needle: str]: Array
let i = 0
while i < haystack_len
if i <= haystack_len - needle_len
let match: bool = true
let match = true
for j in 0..needle_len
if haystack[i + j] != needle[j]
match = false
@@ -580,8 +578,8 @@ func str.split[haystack: str, needle: str]: Array
return result
func str.reverse[s: str] : str
let len: i64 = str.len(s)
let out: str = mem.alloc(len + 1) as str
let len = str.len(s)
let out = mem.alloc(len + 1) as str
for i in 0..len
out[i] = s[len - i - 1]
@@ -590,7 +588,7 @@ func str.reverse[s: str] : str
func str.from_i64[n: i64] : str
if n == 0
let out: str = mem.alloc(2) as str
let out = mem.alloc(2) as str
out[0] = '0'
out[1] = 0
return out
@@ -601,7 +599,7 @@ func str.from_i64[n: i64] : str
if n == -9223372036854775808
return str.make_copy("-9223372036854775808")
n = -n
let buf: str = mem.alloc(21) as str // enough to fit -MAX_I64
let buf = mem.alloc(21) as str // enough to fit -MAX_I64
let end = 20
buf[end] = 0
end = end - 1
@@ -612,21 +610,21 @@ func str.from_i64[n: i64] : str
if neg
buf[end] = '-'
end = end - 1
let s: str = str.make_copy((buf as ptr + end + 1) as str)
let s = str.make_copy((buf as ptr + end + 1) as str)
mem.free(buf)
return s
func str.hex_from_i64[n: i64] : str
let hex_chars: str = "0123456789abcdef"
let hex_chars = "0123456789abcdef"
if n == 0
let out: str = mem.alloc(2) as str
let out = mem.alloc(2) as str
out[0] = '0'
out[1] = 0
return out
let mask: i64 = (1 << 60) - 1
let buf: str = mem.alloc(17) as str
let mask = (1 << 60) - 1
let buf = mem.alloc(17) as str
let len = 0
while n != 0
@@ -634,7 +632,7 @@ func str.hex_from_i64[n: i64] : str
n = (n >> 4) & mask
len = len + 1
let out: str = mem.alloc(len + 1) as str
let out = mem.alloc(len + 1) as str
let j = 0
while j < len
out[j] = buf[len - 1 - j]
@@ -645,13 +643,13 @@ func str.hex_from_i64[n: i64] : str
return out
func str.from_char[c: u8] : str
let s: str = mem.alloc(2) as str
let s = mem.alloc(2) as str
s[0] = c
s[1] = 0
return s
func str.parse_i64[s: str] : i64
let len: i64 = str.len(s)
let len = str.len(s)
let i = 0
let sign = 1
@@ -661,7 +659,7 @@ func str.parse_i64[s: str] : i64
let num = 0
while i < len
let d: u8 = s[i]
let d = s[i]
if d < '0' || d > '9'
break
num = num * 10 + (d - '0')
@@ -669,11 +667,11 @@ func str.parse_i64[s: str] : i64
return num * sign
func str.hex_encode[s: str, s_len: i64] : str
let hex_chars: str = "0123456789abcdef"
let out: str = mem.alloc(s_len * 2 + 1) as str
let hex_chars = "0123456789abcdef"
let out = mem.alloc(s_len * 2 + 1) as str
for i in 0..s_len
let b: u8 = s[i]
let b = s[i]
out[i * 2] = hex_chars[(b >> 4) & 15]
out[i * 2 + 1] = hex_chars[b & 15]
@@ -689,16 +687,16 @@ func str._hex_digit_to_int[d: u8] : u8
panic("invalid hex digit passed to str._hex_digit_to_int")
func str.hex_decode[s: str] : str
let s_len: i64 = str.len(s)
let s_len = str.len(s)
if s_len % 2 != 0
panic("invalid hex string passed to str.hex_decode")
let out_len: i64 = s_len / 2
let out: str = mem.alloc(out_len + 1) as str
let out_len = s_len / 2
let out = mem.alloc(out_len + 1) as str
for i in 0..out_len
let high: u8 = str._hex_digit_to_int(s[i * 2])
let low: u8 = str._hex_digit_to_int(s[i * 2 + 1])
let high = str._hex_digit_to_int(s[i * 2])
let low = str._hex_digit_to_int(s[i * 2 + 1])
out[i] = (high << 4) | low
out[out_len] = 0
@@ -708,7 +706,7 @@ func math.gcd[a: i64, b: i64] : i64
a = math.abs(a)
b = math.abs(b)
while b != 0
let tmp: i64 = b
let tmp = b
b = a % b
a = tmp
return a
@@ -755,8 +753,8 @@ func math.isqrt[n: i64] : i64
if n == 0 || n == 1
return n
let guess: i64 = n
let next_guess: i64 = (guess + n / guess) / 2
let guess = n
let next_guess = (guess + n / guess) / 2
while next_guess < guess
guess = next_guess
@@ -788,7 +786,7 @@ func array.new[] : Array
return new Array
func array.new_preallocated_and_zeroed[size: i64] : Array
let xs: Array = new Array
let xs = new Array
if size > 0
xs->data = must(mem.realloc?(xs->data, size * 8)) as ptr
mem.zero(xs->data, size * 8)
@@ -833,13 +831,13 @@ func array.slice[xs: Array, start: i64, length: i64] : Array
if start < 0 || length < 0 || start + length > xs->size
panic("array.slice out of bounds")
let new_array: Array = array.new_preallocated_and_zeroed(length)
let new_array = array.new_preallocated_and_zeroed(length)
for i in 0..length
array.set(new_array, i, array.nth(xs, start + i))
return new_array
func array.concat[a: Array, b: Array] : Array
let new_array: Array = array.new_preallocated_and_zeroed(a->size + b->size)
let new_array = array.new_preallocated_and_zeroed(a->size + b->size)
for i in 0..a->size
array.set(new_array, i, array.nth(a, i))
for i in 0..b->size
@@ -857,12 +855,12 @@ struct HashMap._Node
next: HashMap._Node
func HashMap.new[] : HashMap
let map: HashMap = new HashMap
let map = new HashMap
map->table = array.new_preallocated_and_zeroed(HashMap._TABLE_SIZE)
return map
func HashMap.insert[map: HashMap, key: str, value: any] : void
let index: i64 = HashMap._djb2(key)
let index = HashMap._djb2(key)
let current: HashMap._Node = array.nth(map->table, index)
while current as ptr
@@ -871,7 +869,7 @@ func HashMap.insert[map: HashMap, key: str, value: any] : void
return 0
current = current->next
let new_node: HashMap._Node = new HashMap._Node
let new_node = new HashMap._Node
new_node->key = str.make_copy(key)
new_node->value = value
new_node->next = array.nth(map->table, index)
@@ -879,7 +877,7 @@ func HashMap.insert[map: HashMap, key: str, value: any] : void
func HashMap.get?[map: HashMap, key: str] : any
err.clear()
let index: i64 = HashMap._djb2(key)
let index = HashMap._djb2(key)
let current: HashMap._Node = array.nth(map->table, index)
while current as ptr
@@ -891,9 +889,9 @@ func HashMap.get?[map: HashMap, key: str] : any
return 0
func HashMap.delete[map: HashMap, key: str] : void
let index: i64 = HashMap._djb2(key)
let index = HashMap._djb2(key)
let current: HashMap._Node = array.nth(map->table, index)
let prev: HashMap._Node = 0 as HashMap._Node
let prev = 0 as HashMap._Node
while current as ptr
if str.equal(current->key, key)
@@ -910,8 +908,8 @@ func HashMap.delete[map: HashMap, key: str] : void
current = current->next
func HashMap._djb2[key: str] : i64
let hash: i64 = 5381
let key_len: i64 = str.len(key)
let hash = 5381
let key_len = str.len(key)
for i in 0..key_len
hash = ((hash << 5) + hash) + key[i]
hash = (hash & 0x7fffffffffffffff) // prevent negative
@@ -921,7 +919,7 @@ func HashMap.free[map: HashMap] : void
for i in 0..HashMap._TABLE_SIZE
let current: HashMap._Node = array.nth(map->table, i)
while current as ptr
let tmp: HashMap._Node = current
let tmp = current
current = current->next
mem.free(tmp->key)
mem.free(tmp)
@@ -934,13 +932,13 @@ func alg.quicksort[arr: Array] : void
func alg._do_quicksort[arr: Array, low: i64, high: i64] : void
if low < high
let i: i64 = alg._partition(arr, low, high)
let i = alg._partition(arr, low, high)
alg._do_quicksort(arr, low, i - 1)
alg._do_quicksort(arr, i + 1, high)
func alg._partition[arr: Array, low: i64, high: i64] : i64
let pivot: i64 = array.nth(arr, high)
let i: i64 = low - 1
let i = low - 1
for j in (low)..high
if array.nth(arr, j) as i64 <= pivot
i = i + 1
@@ -960,13 +958,13 @@ func alg.count[arr: Array, item: any] : i64
return count
func alg.map[arr: Array, fn: fnptr] : Array
let out: Array = array.new_preallocated_and_zeroed(arr->size)
let out = array.new_preallocated_and_zeroed(arr->size)
for i in 0..arr->size
array.set(out, i, fn(array.nth(arr, i)))
return out
func alg.filter[arr: Array, fn: fnptr] : Array
let out: Array = []
let out = []
for i in 0..arr->size
if fn(array.nth(arr, i))
array.push(out, array.nth(arr, i))
@@ -991,7 +989,7 @@ func os.sleep[ms: i64] : void
if ms < 0
panic("negative time passed to os.sleep")
// TODO: we really shouldnt need a heap allocation to sleep
let req: os.Timespec = new os.Timespec
let req = new os.Timespec
req->tv_sec = ms / 1000
req->tv_nsec = (ms % 1000) * 1000000
_builtin_syscall(SYS_nanosleep, req, 0)
@@ -999,17 +997,17 @@ func os.sleep[ms: i64] : void
func os.urandom?[n: i64]: ptr
err.clear()
let buffer: ptr = mem.alloc(n)
let buffer = mem.alloc(n)
if err.check()
return 0 as ptr
let fd: i64 = _builtin_syscall(SYS_openat, -100, "/dev/urandom", 0, 0)
let fd = _builtin_syscall(SYS_openat, -100, "/dev/urandom", 0, 0)
if fd < 0
mem.free(buffer)
err.set(ERR_OPEN_FAILED, "os.urandom?: failed to open /dev/urandom")
return 0 as ptr
let bytes_read: i64 = _builtin_syscall(SYS_read, fd, buffer, n)
let bytes_read = _builtin_syscall(SYS_read, fd, buffer, n)
_builtin_syscall(SYS_close, fd)
if n != bytes_read
@@ -1021,7 +1019,7 @@ func os.urandom?[n: i64]: ptr
func os.urandom_i64[]: i64
let buffer: ptr = must(os.urandom?(8))
let n: i64 = mem.read64(buffer)
let n = mem.read64(buffer)
mem.free(buffer)
return n
@@ -1031,31 +1029,31 @@ struct os.Timeval
func os.time[] : i64
// TODO: we really shouldnt need a heap allocation to check the time
let tv: os.Timeval = new os.Timeval
let tv = new os.Timeval
_builtin_syscall(SYS_gettimeofday, tv, 0)
let out: i64 = tv->tv_sec * 1000 + tv->tv_usec / 1000
let out = tv->tv_sec * 1000 + tv->tv_usec / 1000
mem.free(tv)
return out
// voodoo magic
func os.run_shell_command?[command: str] : i64
err.clear()
let pid: i64 = _builtin_syscall(SYS_fork)
let pid = _builtin_syscall(SYS_fork)
if pid < 0
err.set(ERR_SYSCALL_FAILED, "os.run_shell_command?: failed to fork")
return -1
if pid == 0
let argv: Array = ["sh", "-c", command, 0] // gets freed after child process exits
let argv = ["sh", "-c", command, 0] // gets freed after child process exits
_builtin_syscall(SYS_execve, "/bin/sh", argv->data, _builtin_environ())
_builtin_syscall(SYS_exit, 1)
else
let status = 0
let wp: i64 = _builtin_syscall(SYS_wait4, pid, ^status, 0, 0)
let wp = _builtin_syscall(SYS_wait4, pid, ^status, 0, 0)
if wp < 0
err.set(ERR_SYSCALL_FAILED, "os.run_shell_command?: wait() failed")
return -1
let st: i64 = status & 0xffffffff
let st = status & 0xffffffff
if (st & 0x7f) == 0
return (st >> 8) & 0xff
@@ -1064,15 +1062,15 @@ func os.run_shell_command?[command: str] : i64
func os.list_directory?[path: str] : Array
err.clear()
let fd: i64 = _builtin_syscall(SYS_openat, -100, path, 0, 0)
let fd = _builtin_syscall(SYS_openat, -100, path, 0, 0)
if fd < 0
err.set(ERR_OPEN_FAILED, "os.list_directory?: failed to open dir")
return 0 as Array
let files: Array = []
let buf: ptr = mem.alloc(1024)
let files = []
let buf = mem.alloc(1024)
while true
let n: i64 = _builtin_syscall(SYS_getdents64, fd, buf, 1024)
let n = _builtin_syscall(SYS_getdents64, fd, buf, 1024)
if n < 0
mem.free(buf)
@@ -1088,10 +1086,10 @@ func os.list_directory?[path: str] : Array
let pos = 0
while pos < n
let len: i64 = mem.read16(buf + pos + 16)
let len = mem.read16(buf + pos + 16)
let name: ptr = buf + pos + 19
if name[0]
let skip: bool = false
let skip = false
// skip if name is exactly '.' or '..'
if name[0] == '.'
if name[1] == 0

View File

@@ -71,6 +71,7 @@ impl Env {
pub struct TypeChecker<'a> {
symbol_table: &'a SymbolTable,
pub expr_types: HashMap<usize, String>,
current_function_return_type: String,
}
@@ -78,6 +79,7 @@ impl<'a> TypeChecker<'a> {
pub fn new(symbol_table: &'a SymbolTable) -> TypeChecker<'a> {
TypeChecker {
symbol_table,
expr_types: HashMap::new(),
current_function_return_type: String::new(),
}
}
@@ -262,8 +264,8 @@ impl<'a> TypeChecker<'a> {
Ok(())
}
pub fn typecheck_expr(&self, env: &mut Env, expr: &Expr) -> Result<Type, ZernError> {
match &expr.kind {
pub fn typecheck_expr(&mut self, env: &mut Env, expr: &Expr) -> Result<Type, ZernError> {
let expr_type = match &expr.kind {
ExprKind::Binary { left, op, right } => {
let left_type = self.typecheck_expr(env, left)?;
@@ -517,7 +519,10 @@ impl<'a> TypeChecker<'a> {
}
Ok(type_name.lexeme.clone())
}
}
}?;
self.expr_types.insert(expr.id, expr_type.clone());
Ok(expr_type)
}
fn is_valid_type_name(&self, name: &str) -> bool {

14
test.zr
View File

@@ -1,6 +1,6 @@
func run_test[x: str] : void
let build_blacklist: Array = ["examples/puzzles", "examples/raylib.zr", "examples/chip8.zr", "examples/sqlite_todo.zr"]
let run_blacklist: Array = ["/aoc", "guess_number.zr", "tcp_server.zr", "udp_server.zr"]
let build_blacklist = ["examples/puzzles", "examples/raylib.zr", "examples/chip8.zr", "examples/sqlite_todo.zr"]
let run_blacklist = ["/aoc", "guess_number.zr", "tcp_server.zr", "udp_server.zr"]
for i in 0..build_blacklist->size
if str.equal(x, array.nth(build_blacklist, i))
@@ -9,10 +9,10 @@ func run_test[x: str] : void
io.printf("Building %s...\n", x)
let build_start_time: i64 = os.time()
let build_start_time = os.time()
if must(os.run_shell_command?(str.concat("./target/release/zern ", x))) != 0
os.exit(1)
let build_end_time: i64 = os.time()
let build_end_time = os.time()
io.printf("%dms\n", build_end_time - build_start_time)
@@ -25,14 +25,14 @@ func run_test[x: str] : void
io.printf("Running %s...\n", x)
let run_cmd: str = "./out"
let run_cmd = "./out"
if str.equal(x, "examples/curl.zr")
run_cmd = str.concat(run_cmd, " http://example.com")
let run_start_time: i64 = os.time()
let run_start_time = os.time()
if must(os.run_shell_command?(run_cmd)) != 0
os.exit(1)
let run_end_time: i64 = os.time()
let run_end_time = os.time()
io.printf("Running %s took %dms\n", x, run_end_time - run_start_time)