prog8 icon indicating copy to clipboard operation
prog8 copied to clipboard

[Feature Request] `const sub`

Open electricbrass opened this issue 10 months ago • 4 comments

I would like to see something similar to C++'s constexpr functions. As Prog8's const is more similar to constexpr, I would suggest this be spelled as const sub. Due to the difference's between the languages and out of understanding that it is not something trivial to implement, I think restricting it to the same limitations constexpr functions had in C++11 would make sense: such a subroutine could only consist of a single return statement, which itself can be evaluated as a constant expression as long as all arguments are themselves constants.

If a const subroutine is called with constant arguments, the entire expression should be evaluated at compile time. If a const subroutine is called with variable arguments, the return statement would instead be inlined to the call site. I believe this should avoid the issues inlining regular subroutines had in earlier versions of Prog8.

Examples:

; const sub that replicates the common BIT macro in C
const sub BIT(ubyte shift) -> uword {
    return 1 << shift
}

const uword foo = BIT(3) ; at compile time the right hand size would evaluate to 0x08

ubyte shiftvar = 3
uword bar = BIT(shiftvar) ; the right hand side would be expanded to 1 << shiftvar

ubyte shiftvar = 3
const uword bar = BIT(shiftvar) ; compilation error

const ubyte shiftconst = 3
uword baz = BIT(shiftconst) ; at compile time the right hand size would evaluate to 0x08

If this is seen as something desirable, I can try implementing it myself when I have some time.

inline sub with the same restrictions but allowing for referencing variables in the return statement could also be useful.

electricbrass avatar Feb 19 '25 23:02 electricbrass

I'll have to think about this some more, but notice that inlining subroutine calls on 6502 is problematic in general due to code size blowup. We only have a few tens of Kilobytes program size to work with

irmen avatar Feb 20 '25 22:02 irmen

That is one of the reasons I'm suggesting limiting the bodies to only a single return statement and nothing else (and I suppose defining constants inside them wouldnt hurt anything either).

electricbrass avatar Feb 21 '25 05:02 electricbrass

Just a heads-up, all time is currently being spent on adding structs and typed pointer support. Thinking about the const sub feature has to wait till after.

irmen avatar Apr 28 '25 22:04 irmen

No rush at all. Structs will be very nice to have.

electricbrass avatar Apr 28 '25 22:04 electricbrass