prologin/stechec2

Generator: support constants of arbitrary types

LeSeulArtichaut opened this issue · 5 comments

Currently constants can only hold a value of type int or double. It might be useful to be able to have constants of any type, including the primitive types (int, double, bool), strings, arrays, structs and enums.

seirl commented

Hmm, I'm pretty sure this won't work for C where constants are implemented as preprocessor macros.

Definitely not a C expert but I've tested it and it looks like you can have struct initializers in preprocessor macros. This compiles:

#include <stdbool.h>

#define SIMPLE { .field_i = 42, .field_bool = true, .field_double = 42.42, .field_string = "TTY" }

/// Simple structure with nothing special.
typedef struct simple_struct
{
    int field_i; ///< Integer field
    bool field_bool; ///< Bool field
    double field_double; ///< Double field
    char* field_string; ///< String field
} simple_struct;

int main()
{
    simple_struct simple = SIMPLE;
    return 0;
}
seirl commented

You're right, that should work.

I guess we also need to settle on a format to specify "values" in the yaml for complex types, but that should be straightforward too/

Actually, array/struct initializers in macros might be the wrong way to go, because, since they are not expressions, you can't access one of their elements/fields:

int i = SIMPLE.field_i;  // error

A solution might be to use global const variables? Or #define for primitives and const for structs and arrays?

I guess we also need to settle on a format to specify "values" in the yaml for complex types, but that should be straightforward too

The only potential problem I can see is that there is no easy way to represent an "identifier" in YAML. If we want to allow enum variants to be used in constants, or if we want to be able to reference other constants, we need to be able to disambiguate between an identifier to another object in the game and a string literal. I'm not sure however that these constructs would be useful.