Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feature Request] const sub #162

Open
electricbrass opened this issue Feb 19, 2025 · 2 comments
Open

[Feature Request] const sub #162

electricbrass opened this issue Feb 19, 2025 · 2 comments

Comments

@electricbrass
Copy link
Contributor

electricbrass commented Feb 19, 2025

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.

@irmen
Copy link
Owner

irmen commented Feb 20, 2025

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

@electricbrass
Copy link
Contributor Author

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).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants