feat: generate C struct info
This commit is contained in:
34
src/main.c
34
src/main.c
@@ -1,3 +1,4 @@
|
|||||||
|
#include <ctype.h>
|
||||||
#include <stdbool.h>
|
#include <stdbool.h>
|
||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
#include <string.h>
|
#include <string.h>
|
||||||
@@ -118,6 +119,35 @@ void print_struct(Struct_Info info) {
|
|||||||
printf("]\n");
|
printf("]\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#define gen(...) do { \
|
||||||
|
fprintf(stream, __VA_ARGS__); \
|
||||||
|
fprintf(stream, " // %s:%d\n", __FILE__, __LINE__); \
|
||||||
|
} while(0)
|
||||||
|
|
||||||
|
char* to_lowercase(char* str) {
|
||||||
|
size_t len = strlen(str);
|
||||||
|
for(size_t i = 0; i < len; i += 1) {
|
||||||
|
str[i] = tolower(str[i]);
|
||||||
|
}
|
||||||
|
return str;
|
||||||
|
}
|
||||||
|
|
||||||
|
void generate_struct_info(FILE* stream, Struct_Info info) {
|
||||||
|
char* lowercase_name = to_lowercase(strdup(info.name));
|
||||||
|
|
||||||
|
gen("static Struct_Info %s_info = {", lowercase_name);
|
||||||
|
gen(" .name = \"%s\",", info.name);
|
||||||
|
gen(" .fields_count = %zu,", info.fields_count);
|
||||||
|
gen(" .fields = (Field_Info[%zu]) {", info.fields_count);
|
||||||
|
for (size_t i = 0; i < info.fields_count; i += 1) {
|
||||||
|
gen(" { .type = \"%s\", .name = \"%s\" },", info.fields[i].type, info.fields[i].name);
|
||||||
|
}
|
||||||
|
gen(" },");
|
||||||
|
gen("};");
|
||||||
|
|
||||||
|
free(lowercase_name);
|
||||||
|
}
|
||||||
|
|
||||||
int main(void)
|
int main(void)
|
||||||
{
|
{
|
||||||
const char *source = "typedef struct { int int_field; bool bool_field; } My_Struct;";
|
const char *source = "typedef struct { int int_field; bool bool_field; } My_Struct;";
|
||||||
@@ -126,8 +156,10 @@ int main(void)
|
|||||||
|
|
||||||
Struct_Info info = {0};
|
Struct_Info info = {0};
|
||||||
if (!parse_struct(&info)) return 1;
|
if (!parse_struct(&info)) return 1;
|
||||||
|
printf("--- Parsed ------------\n");
|
||||||
print_struct(info);
|
print_struct(info);
|
||||||
|
printf("--- Generated ---------\n");
|
||||||
|
generate_struct_info(stdout, info);
|
||||||
|
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user