Files
cig/json.c
T
roodletoof 657889c2b3 some progress
some progress
2026-10-03 17:21:16 +02:00

107 lines
2.5 KiB
C

#include "cig.h"
#include <string.h>
bool json_parse(scanner_t *scanner, allocator_t allocator, json_value_t *out) {
scan_whitespace(scanner);
scan_result_t str_result = scan_string_literal(scanner);
if (str_result.ok) {
const char *buffer = str_result.value.string_literal;
size_t length = strlen(buffer);
char *buff_copy = allocator_alloc(allocator, length+1);
strncpy(buff_copy, buffer, length+1);
buff_copy[length] = '\0';
*out = (json_value_t) {
.type=json_type_string,
.string=(json_string_t) { .length=length, .buffer=buff_copy }
};
return true;
}
scan_result_t f64_result = scan_f64(scanner);
if (f64_result.ok) {
*out = (json_value_t) {
.type=json_type_number,
.number=f64_result.value.f64
};
return true;
}
scan_result_t i64_result = scan_i64(scanner);
if (i64_result.ok) {
*out = (json_value_t) {
.type=json_type_number,
.number=(double)i64_result.value.i64
};
return true;
}
scan_result_t true_result = scan_literal(scanner, "true");
if (true_result.ok) {
*out = (json_value_t) {
.type=json_type_boolean,
.boolean=true
};
return true;
}
scan_result_t false_result = scan_literal(scanner, "false");
if (false_result.ok) {
*out = (json_value_t) {
.type=json_type_boolean,
.boolean=false
};
return true;
}
scan_result_t null_result = scan_literal(scanner, "null");
if (null_result.ok) {
*out = (json_value_t) { .type=json_type_null, };
return true;
}
scan_result_t arr_open_result = scan_literal(scanner, "[");
if (arr_open_result.ok) {
json_value_t *values = make_arr(json_value_t, allocator);
do {
scan_whitespace(scanner);
json_value_t val;
bool ok = json_parse(scanner, allocator, &val);
if (!ok) {
return false;
}
arr_append(values, val);
scan_whitespace(scanner);
} while(scan_literal(scanner, ",").ok);
*out = (json_value_t) {
.type=json_type_array,
.array=(json_array_t){
.values=values,
.length=arr_len(values),
},
};
scan_result_t arr_close_result = scan_literal(scanner, "]");
return arr_close_result.ok;
}
// TODO: arrays and objects are allowed to contain nothing...
scan_result_t obj_open_result = scan_literal(scanner, "{");
if (obj_open_result.ok) {
json_pair_t *pairs = make_arr(json_pair_t, allocator);
// TODO: continue here
do {
scan_whitespace(scanner);
scan_result_t key_result = scan_string_literal(scanner);
} while(scan_literal(scanner, ",").ok);
}
typedef struct json_pair {
json_string_t key;
json_value_t value;
} json_pair_t;
}