ameliatastic / seahorse-lang

Write Anchor-compatible Solana programs in Python
Apache License 2.0
313 stars 43 forks source link

Add constants #85

Closed ameliatastic closed 1 year ago

ameliatastic commented 1 year ago

Finally taking on the oldest standing issue: constants.

We talked about the advantages/disadvantages of including typing in Discord. Right this branch is dedicated to the "untyped constants" approach, which makes the Seahorse-facing UX a little smoother and more Python-native, at the expense of generated code readability.

Closes #2

ameliatastic commented 1 year ago

A bit about take 1: I had the idea to leverage the Rust compiler to take care of some of my concerns about generated code for untyped constants. Instead of expanding the constants within the Seahorse compiler, each constant gets its own macro defined which lets the Rust compiler perform the expansion for us.

So you can write code like this:

MIN = 2
MAX = 16
RANGE = MAX - MIN

# Using the consts

for i in range(MIN, MAX):
  # ...

...which generates something like this:

seahorse_const! { MIN, 2 }
seahorse_const! { MAX, 16 }
seahorse_const! { MAX!() - MIN!() }

// Using the consts

for i in MIN!()..MAX!() {
  // ...
}

seahorse_const! is a macro that expands to another macro, in this case the macro defs for MIN, MAX, and RANGE. It's just there to clean up the generated code a bit, like assign! and related macros.

ameliatastic commented 1 year ago

Good idea, definitely need to expand the tests.

Last thing I'm gonna add (beyond the test) is something to make sure that the expressions that qualify as constants are limited. General rules I'm thinking of is to not call functions, including constructors (which further includes list constructors). Just something to make sure that constants don't get too hectic.