TelluIoT / ThingML

The ThingML modelling language
https://github.com/TelluIoT/ThingML
Apache License 2.0
102 stars 32 forks source link

More convenient initialization of struct and array properties in the C compiler #139

Open jakhog opened 7 years ago

jakhog commented 7 years ago

The problem

Consider the following ThingML code

datatype Byte<1>
   @c_type "uint8_t";

datatype BTAddress<6>
    @c_type "bdaddr_t"
    @c_header "#include <bluetooth/bluetooth.h>;

thing MyThing
{
    property Number : Byte = '0xFF'
    property Address : BTAddress = '{ 0x00, 0xDE, 0xAD, 0xBE, 0xEF, 0x00 }'
}

configuration MyConf
{
    instance MyThingInst : MyThing
}

where bdaddr_t is defined in bluetooth/bluetooth.h as

/* BD Address */
typedef struct {
    uint8_t b[6];
} __attribute__((packed)) bdaddr_t;

The ThingML code is valid - and makes sense - but the resulting C-code from the Posix compiler will not compile, since the struct MyThing_Instance MyThingInst_var is declared in the MyConf_cfg.c file, while it is assigned in the void initialize_configuration_MyConf() function. As depicted in the following snippet of the resulting MyConf_cfg.c file:

...
struct MyThing_Instance MyThingInst_var;
...
void initialize_configuration_MyConf() {
    ...
    MyThingInst_var.MyThing_Number_var = 0xFF;
    MyThingInst_var.MyThing_Address_var = { 0x00, 0xDE, 0xAD, 0xBE, 0xEF, 0x00 };
    ...
}
...

The above code works for basic types, but not arrays and structs.

The current workaround is a mess of declaring some temporary global variables in a @c_header annotation in the configuration, and initializing them in a @c_global annotation in the configuration.

A solution

A better way of initializing properties of things in C, would be to initialize the Thing-struct in the declaration, like this:

...
struct MyThing_Instance MyThingInst_var = {
    .MyThing_Number_var = 0xFF,
    .MyThing_Address_var = { 0x00, 0xDE, 0xAD, 0xBE, 0xEF, 0x00 },
};
...
void initialize_configuration_MyConf() {
    ...
}
...

Which would be valid C-code.

This should also be implemented to work when the values of properties are set in the ThingML configuration, like this:

...
configuration MyConf
{
    instance MyThingInst : MyThing
    set MyThingInst.Address = '{ 0x00, 0xBA, 0xAD, 0xF0, 0x0D, 0x00 }'
}