add extending-structs.jt, struct-functions.jt

also sockets.jt lol
This commit is contained in:
Luna 2019-03-08 18:45:33 -03:00
parent a4685423a4
commit 2d91393a1c
6 changed files with 92 additions and 4 deletions

View File

@ -0,0 +1,15 @@
struct A {
int a,
int b
}
struct B <- A {
int c
}
fn main () {
a := A{1, 2}
b := B{1, 2, 3}
}

View File

@ -13,4 +13,3 @@ fn main () {
my_puts(2)
my_puts("aaa")
}

View File

@ -1,6 +1,10 @@
import io
// if a return type is not defined, it is implicitly void and so the function
// returns nil (the only instance of void)
// main can return int or void, void mains are handled by jortsc
fn main () -> int {
io.puts("pant")
ret 0
io.puts("pants")
0
}

10
examples/sockets.jt Normal file
View File

@ -0,0 +1,10 @@
import socket
import io
fn main () {
sock := socket.tcp_connect("example.com", 80)
sock.send("HTTP/1.1\n")
frame := sock.recv(1024)
sock.close()
io.puts(frame)
}

View File

@ -7,7 +7,7 @@ fn main () {
s := "this is {s}"
io.puts(s)
s + 2 // invalid
s := s + 2 // invalid
// this however, is valid, there is an io.puts that handles int,
// more on function overload in a bit

View File

@ -0,0 +1,60 @@
import io
struct A {
int val1,
int val2
}
// self is injected and represents the struct A
// from the functions' definition
fn A:sum_fields() -> int {
self.val1 + self.val2
}
// type of sum_fields is:
// Func ([A] -> int)
// the mut keyword signals that self is a "reference"
// to self, instead of a copy
// however, what actually happens is that an instance of
// A is returned from the function implicitly
fn mut A:incr_both_fields() {
self.val1++
self.val2++
}
// and so, the type becomes:
// Func ([A] -> A)
fn mut A:incr_and_sum () {
self.val1++
self.val2++
self.val1 + self.val2
}
// type is:
// Func ([A] -> (A, int))
fn main () {
a := A{0, 0}
a.incr_both_fields()
/*
translates to:
a := incr_both_fields(a)
*/
sum := a.sum_fields()
io.puts(sum)
val = a.incr_and_sum()
/*
translates to:
a, val := incr_and_sum(a)
*/
}