Akuli / jou

Yet another programming language
MIT License
11 stars 4 forks source link

Compile time struct #493

Closed Moosems closed 6 months ago

Moosems commented 6 months ago

?

littlewhitecloud commented 6 months ago

Akuli commented 6 months ago

What problem would this solve, and how would this work?

Moosems commented 6 months ago

Performance enhancements by requiring less work during runtime and greater optimizations. Generally for speed-intensive operations the more that can be optimized at compile time, the better.

Akuli commented 6 months ago

I'd say this is already implemented. Jou uses LLVM for optimizations, and LLVM can get rid of class instantiations in some cases.

For example, consider:

class Point:
    x: int
    y: int

def get_sum(x: int, y: int) -> int:
    p = Point{x=x, y=y}
    return p.x + p.y

If I try to run this with all optimizations turned on and verbose-verbose (-O3 -vv), I get output that ends with:

===== Optimized LLVM IR for file "a.jou" =====
; ModuleID = 'a.jou'
source_filename = "a.jou"
target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128"
target triple = "x86_64-pc-linux-gnu"

; Function Attrs: mustprogress nofree nosync nounwind readnone willreturn
define i32 @get_sum(i32 %0, i32 %1) local_unnamed_addr #0 {
block0:
  %signed_op = add i32 %1, %0
  ret i32 %signed_op
}

attributes #0 = { mustprogress nofree nosync nounwind readnone willreturn }

Emitting object file: ./jou_compiled/a/a.o
Running linker: '/usr/lib/llvm-14/bin/clang' "./jou_compiled/a/_assert_fail.o" "./jou_compiled/a/a.o" -o './jou_compiled/a/a' -lm 
/usr/bin/ld: /lib/x86_64-linux-gnu/Scrt1.o: in function `_start':
(.text+0x17): undefined reference to `main'
clang: error: linker command failed with exit code 1 (use -v to see invocation)

The relevant part is:

define i32 @get_sum(i32 %0, i32 %1) local_unnamed_addr #0 {
block0:
  %signed_op = add i32 %1, %0
  ret i32 %signed_op
}

So LLVM turned the get_sum() function into basically def get_sum(x, y): return y + x. Here add i32 means the + operator for 32-bit numbers, and %1 and %0 are the arguments of the function. (I do not know why the order is reversed.)

The output ends with a linker error because I didn't define a main() function.

Moosems commented 6 months ago

Beautiful. I wasn't sure if it would do that in Jou. To understand what I meant take a look at the difference from def and fn or class and struct in Jou which optimizes them differently.

Akuli commented 6 months ago

I still don't know what you're talking about. Jou doesn't have struct or fn keywords, and that would be irrelevant anyway, because the optimizer doesn't know anything about Jou's syntax anyway.

But it seems like Jou does what you wanted it to do.