Files
corelang/examples/order_independent_declarations.core
2026-03-20 08:35:18 +01:00

75 lines
2.3 KiB
Core

/*
Biggest problems with C/C++ are the header files and the fact that
top level declarations are required to be ordered.
In C++ you simply cannot write code like this:
struct Asset{
Asset_Tag asset_tag;
};
enum Asset_Tag{
ASSET_SOUND,
ASSET_IMAGE,
};
Even though it makes more sense to do that, I would rather first learn
about what Asset is rather then what tags it can have. C/C++ force on you
an order of declarations that doesn't match what you have in your head.
The next problem are the header files. Frequently on top of writing code,
in C/C++ there is a need to maintain a header file. Header files contain
all the forward declarations of the functions that you are implementing.
Problem with this is that if you are changing something, potentially
you now need to change that in multiple places. It would be nice if I could
write a module that doesn't yet have any concrete spec but the functions
are available everywhere, immediately. On top of that those functions would
be nicely localized in a single file without thinking about what depends
on what, how to fit it in the stack of includes etc. It would be just nice
to tell the compiler to solve all those issues for us.
*/
// We can have main at the top level, this is something
// that is sometimes pretty tricky in C++
main :: (): int
// Even though Asset is beneath main, this still works
// this feature is even nicer when we think about modules etc.
asset1 := make_sound()
asset2 := make_sound()
asset1.next_asset = &asset2
return 0
// @todo: This does not work
// asset := []Asset{make_sound(), make_sound()}
// asset[0].next_sound = &asset[1]
// Recursion is a pain point for this kinds of algorithms
// As can be seen here it works very nicely
make_sound :: (should_exit_recursion: bool = false): Asset
if should_exit_recursion == true
asset: Asset
asset.tag = Asset_Tag.Sound
return asset
return make_sound(true)
Asset :: struct
tag: Asset_Tag
// Pointers to self work as expected
// this is always a pain point for these kinds of
// algorithms
next_asset: *Asset
// enum #flag assigns default values differently from normal enums.
// It assigns a unique bit of a value to each enumeration.
// Default values go: 1, 2, 4, 8, 16, 32, 64
Asset_Tag :: enum #flag
Sound
Image
Text