Compare commits

..

20 Commits

Author SHA1 Message Date
5cb121d1de List_TomlValue_destroyWithElements 2025-12-21 20:26:00 +05:00
559902eaf5 updated tlibc 2025-12-21 20:01:27 +05:00
11f16a79fc Merge branch 'main' of https://timerix.ddns.net/git/Timerix/tlibtoml 2025-12-13 03:27:30 +05:00
a15b5a6b32 fixed some errors 2025-12-13 03:27:28 +05:00
bd38585b35 HashMapKeyValue.value -> value_ptr 2025-12-02 20:06:18 +05:00
a0e280d77b updated README.md 2025-11-27 01:45:05 +05:00
6978bb2afe changed TomlValue.value to anonymous union 2025-11-27 01:32:34 +05:00
711cc70b68 fixed DEPENDENCIES_DIR bug in tlibtoml.config 2025-11-27 01:25:35 +05:00
bdcc838bb8 improved error messages in TomlTable_get* 2025-11-27 01:24:27 +05:00
3e21766514 made all toml_load* functions public 2025-11-27 00:31:47 +05:00
7a0570b0b9 added file_readWholeText in toml_load_file 2025-11-26 23:49:40 +05:00
281a65f0d1 replaced TomlArray with tlibc List 2025-11-26 17:02:38 +05:00
2082d56c25 added tlibc error handling everywhere 2025-11-26 16:42:40 +05:00
048542d079 moved functions code to separate files 2025-11-26 16:26:01 +05:00
52870920c1 removed libtoml allocator 2025-11-10 10:42:13 +05:00
c49a8cb1e5 replaced TomlTable with HashMap 2025-11-10 10:31:47 +05:00
a33505ffe4 replaced TomlString with StringBuilder 2025-11-10 05:42:29 +05:00
c83ee4078e replaced char* function arguments with str 2025-11-10 02:30:05 +05:00
247d291da6 fixed some warnings 2025-11-10 01:15:18 +05:00
f889990728 replaced numeric types to those from tlibc 2025-11-10 00:11:41 +05:00
34 changed files with 1773 additions and 2051 deletions

View File

@@ -4,6 +4,7 @@
"name": "all",
"defines": [],
"includePath": [
"src",
"include",
"../tlibc/include",
"${default}"

4
.vscode/launch.json vendored
View File

@@ -5,8 +5,8 @@
"name": "gdb_debug",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/bin/tlibtoml",
"windows": { "program": "${workspaceFolder}/bin/tlibtoml.exe" },
"program": "${workspaceFolder}/bin/test",
"windows": { "program": "${workspaceFolder}/bin/test.exe" },
"preLaunchTask": "build_exec_dbg",
"stopAtEntry": false,
"cwd": "${workspaceFolder}/bin",

View File

@@ -1,21 +1,55 @@
# tlibtoml
A fork of [libtoml](https://github.com/brglng/libtoml) rewritten to use [tlibc](https://timerix.ddns.net/git/Timerix/tlibtoml) instead of its own (worse) implementation of collections and strings. For example, Table from libtoml is just an array of key-value pairs, where search happens by calling `strcmp()` on each element. Such inefficient code hurts my mind, so i have no other choise than to rewrite this library.
A fork of [libtoml](https://github.com/brglng/libtoml) rewritten to use [tlibc](https://timerix.ddns.net/git/Timerix/tlibc) instead of its own (worse) implementation of collections and strings. For example, Table from libtoml is just an array of key-value pairs, where search happens by calling `strcmp()` on each element. Such inefficient code hurts my mind, so i have no other choise than to rewrite this library.
## Build
1. Clone the repository.
1. Clone this repository.
```
git clone https://timerix.ddns.net/git/Timerix/tlibtoml.git
```
2. Install [cbuild](https://timerix.ddns.net/git/Timerix/cbuild.git).
3. Clone [tlibc](https://timerix.ddns.net/git/Timerix/tlibtoml). By default
`dependencies/tlibc.config` expects that `tlibc/` is present in the same directory as `tlibtoml/`.
2. Install [cbuild](https://timerix.ddns.net/git/Timerix/cbuild/releases).
Select latest version compatible with the one in `project.config`.
Example: For `2.3.0` download latest `2.3.x`.
3. Clone [tlibc](https://timerix.ddns.net/git/Timerix/tlibc).
By default `dependencies/tlibc.config` expects that `tlibc/` is present in the same directory as `tlibtoml/`.
If you cloned it to another directory, change `DEPENDENCIES_DIR` in `tlibtoml/project.user.config`.
```
git clone https://timerix.ddns.net/git/Timerix/tlibc.git
```
4. Build and run tests
```
cd tlibtoml
cbuild build_exec exec
```
5. To build library use tasks `build_static_lib[_dbg]` or `build_shared_lib[_dbg]`
6. If you use tlibtoml as static library, add `LINKER_LIBS` from tlibtoml `project.config` to your project.
## Usage
```c
#include "tlibtoml.h"
int main(){
Deferral(32); // reserve memory for 32 defers
// init tlibc global variables
try_fatal_void(tlibc_init());
// init tlibtoml global variables
try_fatal_void(tlibtoml_init());
Defer(tlibc_deinit());
Defer(tlibtoml_deinit());
// load whole file to memory and parse it as toml
try_fatal(TomlTable* t, p, toml_load_filename("example.toml"));
// get value by key and ensure it's a string
try_fatal(str* s, p, TomlTable_get_str(t, STR("some_key")));
// print this string value
printf("some_key = '"FMT_str"'\n", str_unwrap(*s));
Return 0; // call defers
}
```

View File

@@ -9,7 +9,7 @@ if [[ "$TASK" = *_dbg ]]; then
else
dep_build_target="build_static_lib"
fi
DEP_PRE_BUILD_COMMAND="setup_user_config"
DEP_PRE_BUILD_COMMAND=""
DEP_BUILD_COMMAND="cbuild $dep_build_target"
DEP_POST_BUILD_COMMAND=""
DEP_CLEAN_COMMAND="cbuild clean"

165
include/tlibtoml.h Normal file
View File

@@ -0,0 +1,165 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
#include <time.h>
#include "tlibc/tlibc.h"
#include "tlibc/time.h"
#include "tlibc/errors.h"
#include "tlibc/string/str.h"
#include "tlibc/collections/HashMap.h"
#include "tlibc/collections/List.h"
//////////////////////////////////////////////////////////////////////////////
// //
// tlibtoml //
// //
//////////////////////////////////////////////////////////////////////////////
Result(void) tlibtoml_init();
void tlibtoml_deinit();
typedef enum TlibtomlError {
TLIBTOML_OK,
TLIBTOML_ERR_SYNTAX,
TLIBTOML_ERR_UNICODE,
TLIBTOML_ERR_NOT_FOUND,
TLIBTOML_ERR_UNEXPECTED_TYPE,
} TlibtomlError;
ErrorCodePage_declare(TLIBTOML);
typedef DateTime TomlDateTime;
typedef struct HashMap(TomlValue) HashMap(TomlValue);
typedef HashMap(TomlValue) TomlTable;
typedef struct List(TomlValue) List(TomlValue);
typedef List(TomlValue) TomlArray;
//////////////////////////////////////////////////////////////////////////////
// //
// Parser //
// //
//////////////////////////////////////////////////////////////////////////////
/// opens file
Result(TomlTable*) toml_load_filename(cstr filename);
/// @param filename to use in error messages
Result(TomlTable*) toml_load_str_filename(str s, cstr filename);
/// loads whole file in memory
/// @param filename to use in error messages
Result(TomlTable*) toml_load_file_filename(FILE* file, cstr filename);
static inline Result(TomlTable*) toml_load_str(str s){
return toml_load_str_filename(s, "<string>");
}
static inline Result(TomlTable*) toml_load_file(FILE* file){
return toml_load_file_filename(file, "<stream>");
}
/* TODO: implement dump functions
str toml_dump_str(const TomlTable* self, TomlErr *err);
void toml_dump_file(const TomlTable* self, FILE* file, TomlErr *err);
*/
//////////////////////////////////////////////////////////////////////////////
// //
// TomlValue //
// //
//////////////////////////////////////////////////////////////////////////////
typedef enum TomlType {
TLIBTOML_INVALID_TYPE,
TLIBTOML_TABLE,
TLIBTOML_ARRAY,
TLIBTOML_STRING,
TLIBTOML_INTEGER,
TLIBTOML_FLOAT,
TLIBTOML_DATETIME,
TLIBTOML_BOOLEAN,
} TomlType;
str TomlType_toStr(TomlType t);
typedef struct TomlValue {
TomlType type;
union {
i64 i;
f64 f;
bool b;
str* s;
TomlArray* array;
TomlTable* table;
TomlDateTime* dt;
};
} TomlValue;
List_declare(TomlValue);
TomlValue TomlValue_new(TomlType type);
TomlValue TomlValue_new_table(void);
TomlValue TomlValue_new_array(void);
TomlValue TomlValue_new_integer(i64 integer);
TomlValue TomlValue_new_float(f64 flt);
TomlValue TomlValue_new_datetime(void);
TomlValue TomlValue_new_bool(bool b);
/// copies the string
TomlValue TomlValue_copy_str(str s);
/// doesnt copy the string
TomlValue TomlValue_move_str(str s);
void TomlValue_destroy(TomlValue* self);
//////////////////////////////////////////////////////////////////////////////
// //
// TomlTable //
// //
//////////////////////////////////////////////////////////////////////////////
TomlTable* TomlTable_new(void);
void TomlTable_free(TomlTable* self);
static inline void TomlTable_set(TomlTable* self, str key, TomlValue value){
HashMap_pushOrUpdate(self, key, &value);
}
static inline TomlValue* TomlTable_get(const TomlTable* self, const str key){
return HashMap_tryGetPtr(self, key);
}
Result(TomlTable*) TomlTable_get_table(const TomlTable* self, str key);
Result(TomlArray*) TomlTable_get_array(const TomlTable* self, str key);
Result(str*) TomlTable_get_str(const TomlTable* self, str key);
Result(i64) TomlTable_get_integer(const TomlTable* self, str key);
Result(f64) TomlTable_get_float(const TomlTable* self, str key);
Result(bool) TomlTable_get_bool(const TomlTable* self, str key);
Result(TomlDateTime*) TomlTable_get_datetime(const TomlTable* self, str key);
//////////////////////////////////////////////////////////////////////////////
// //
// TomlArray //
// //
//////////////////////////////////////////////////////////////////////////////
TomlArray* TomlArray_new(void);
void TomlArray_free(TomlArray* self);
static inline void TomlArray_append(TomlArray* self, TomlValue value){
List_TomlValue_push(self, value);
}
#ifdef __cplusplus
}
#endif

View File

@@ -1,190 +0,0 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
#include "tlibc/std.h"
#include <time.h>
#if defined(__cplusplus) && __cplusplus >= 201103L
#define ATTRIBUTE_THREAD_LOCAL thread_local
#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
#define ATTRIBUTE_THREAD_LOCAL _Thread_local
#elif defined(_MSC_VER)
#define ATTRIBUTE_THREAD_LOCAL __declspec(thread)
#else
#define ATTRIBUTE_THREAD_LOCAL __thread
#endif
#define TOML_FALSE 0
#define TOML_TRUE 1
typedef enum {
TOML_OK,
TOML_ERR,
TOML_ERR_OS,
TOML_ERR_NOMEM,
TOML_ERR_SYNTAX,
TOML_ERR_UNICODE
} TomlErrCode;
typedef struct {
TomlErrCode code;
char* message;
int _is_literal;
} TomlErr;
typedef struct {
char* str;
size_t len;
size_t _capacity;
} TomlString;
typedef struct _TomlValue TomlValue;
typedef struct {
TomlValue** elements;
size_t len;
size_t _capacity;
} TomlArray;
typedef struct _TomlKeyValue TomlKeyValue;
typedef struct {
size_t _capacity;
size_t len;
TomlKeyValue* _keyvals;
} TomlTable;
typedef struct {
TomlTable* _table;
TomlKeyValue* _keyval;
} TomlTableIter;
typedef enum {
TOML_TABLE,
TOML_ARRAY,
TOML_STRING,
TOML_INTEGER,
TOML_FLOAT,
TOML_DATETIME,
TOML_BOOLEAN,
} TomlType;
struct _TomlValue {
TomlType type;
union {
TomlTable* table;
TomlArray* array;
TomlString* string;
#if defined(_MSC_VER) || defined(__APPLE__)
long long integer;
#else
long integer;
#endif
double float_;
struct tm datetime;
int boolean;
} value;
};
struct _TomlKeyValue {
TomlString* key;
TomlValue* value;
};
typedef struct {
void* (*malloc)(void *context, size_t size);
void* (*realloc)(void *context, void *p, size_t size);
void (*free)(void *context, void *p);
} TomlAllocFuncs;
void toml_set_allocator(void *context, const TomlAllocFuncs *funcs);
void* toml_malloc(size_t size);
void* toml_realloc(void *p, size_t size);
void toml_free(void *p);
char* toml_strdup(const char *str);
char* toml_strndup(const char *str, size_t n);
int toml_vasprintf(char **str, const char *format, va_list args);
int toml_asprintf(char **str, const char *format, ...);
const TomlErr* toml_err(void);
void toml_err_clear(void);
TomlString* toml_string_new(void);
TomlString* toml_string_from_str(const char *str);
TomlString* toml_string_from_nstr(const char *str, size_t len);
void toml_string_append_char(TomlString *self, char ch);
void toml_string_append_str(TomlString *self, const char *str);
void toml_string_append_nstr(TomlString *self, const char *str, size_t len);
TomlString* toml_string_clone(const TomlString *self);
void toml_string_free(TomlString *self);
int toml_string_equals(const TomlString *self, const TomlString *other);
TomlTable* toml_table_new(void);
void toml_table_free(TomlTable *self);
void toml_table_set_by_string(TomlTable *self, TomlString *key, TomlValue *value);
TomlValue *toml_table_get_by_string(const TomlTable *self, const TomlString *key);
void toml_table_set(TomlTable *self, const char *key, TomlValue *value);
void toml_table_setn(TomlTable *self, const char *key, size_t key_len, TomlValue *value);
TomlValue* toml_table_get(const TomlTable *self, const char *key);
TomlTable* toml_table_get_as_table(const TomlTable *self, const char *key);
TomlArray* toml_table_get_as_array(const TomlTable *self, const char *key);
TomlString* toml_table_get_as_string(const TomlTable *self, const char *key);
#if defined(_MSC_VER) || defined(__APPLE__)
long long toml_table_get_as_integer(const TomlTable *self, const char *key);
#else
long toml_table_get_as_integer(const TomlTable *self, const char *key);
#endif
double toml_table_get_as_float(const TomlTable *self, const char *key);
const struct tm* toml_table_get_as_datetime(const TomlTable *self, const char *key);
int toml_table_get_as_boolean(const TomlTable *self, const char *key);
TomlValue* toml_table_getn(const TomlTable *self, const char *key, size_t key_len);
TomlTableIter toml_table_iter_new(TomlTable *table);
TomlKeyValue* toml_table_iter_get(TomlTableIter *self);
int toml_table_iter_has_next(TomlTableIter *self);
void toml_table_iter_next(TomlTableIter *self);
TomlArray* toml_array_new(void);
void toml_array_free(TomlArray *self);
void toml_array_append(TomlArray *self, TomlValue *value);
TomlValue* toml_value_new(TomlType type);
TomlValue* toml_value_new_string(TomlType type);
TomlValue* toml_value_new_table(void);
TomlValue* toml_value_new_array(void);
#if defined(_MSC_VER) || defined(__APPLE__)
TomlValue *toml_value_new_integer(long long integer);
#else
TomlValue *toml_value_new_integer(long integer);
#endif
TomlValue* toml_value_new_float(double flt);
TomlValue* toml_value_new_datetime(void);
TomlValue* toml_value_new_boolean(int boolean);
TomlValue* toml_value_from_str(const char *str);
TomlValue* toml_value_from_nstr(const char *str, size_t len);
void toml_value_free(TomlValue *self);
TomlTable* toml_load_str(const char *str);
TomlTable* toml_load_nstr(const char *str, size_t len);
TomlTable* toml_load_file(FILE *file);
TomlTable* toml_load_filename(const char *filename);
/* TODO: implement dump functions
char *toml_dump_str(const TomlTable *self, TomlErr *err);
TomlString *toml_dump_nstr(const TomlTable *self, TomlErr *err);
void toml_dump_file(const TomlTable *self, FILE *file, TomlErr *err);
*/
#ifdef __cplusplus
}
#endif

View File

@@ -1,5 +1,5 @@
#!/usr/bin/env bash
CBUILD_VERSION=2.3.0
CBUILD_VERSION=2.3.2
PROJECT="tlibtoml"
CMP_C="gcc"
@@ -37,7 +37,7 @@ OBJDIR="obj"
OUTDIR="bin"
STATIC_LIB_FILE="$PROJECT.a"
INCLUDE="-I./include -I../tlibc/include"
INCLUDE="-Isrc -Iinclude -I../tlibc/include"
# OS-specific options
case "$OS" in
@@ -45,8 +45,7 @@ case "$OS" in
EXEC_FILE="test.exe"
SHARED_LIB_FILE="$PROJECT.dll"
INCLUDE="$INCLUDE "
# example: "-lSDL2 -lSDL2_image"
LINKER_LIBS=""
LINKER_LIBS="-luuid"
;;
LINUX)
EXEC_FILE="test"

20
src/TomlArray.c Normal file
View File

@@ -0,0 +1,20 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "toml_internal.h"
TomlArray* TomlArray_new(void)
{
TomlArray* array = (TomlArray*)malloc(sizeof(TomlArray));
*array = List_TomlValue_construct(NULL, 0, 0);
return array;
}
void TomlArray_free(TomlArray* self)
{
if(!self)
return;
List_TomlValue_destroyWithElements(self, TomlValue_destroy);
free(self);
}

102
src/TomlTable.c Normal file
View File

@@ -0,0 +1,102 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "toml_internal.h"
TomlTable* TomlTable_new(void)
{
TomlTable* table = (TomlTable*)malloc(sizeof(TomlTable));
HashMap_construct(table, TomlValue, (Destructor_t)TomlValue_destroy);
return table;
}
void TomlTable_free(TomlTable* self)
{
if(!self)
return;
HashMap_destroy(self);
free(self);
}
#define try_assert_value_found(VAL, KEY) \
if(VAL == NULL){ \
Return RESULT_ERROR_CODE_FMT( \
TLIBTOML, TLIBTOML_ERR_NOT_FOUND, \
"can't find '"FMT_str"'", \
str_unwrap(KEY)); \
} \
#define try_assert_value_type(VAL, KEY, TYPE) \
if((VAL)->type != TYPE){ \
str t_expected_s = TomlType_toStr(TYPE); \
str t_got_s = TomlType_toStr((VAL)->type); \
Return RESULT_ERROR_CODE_FMT( \
TLIBTOML, TLIBTOML_ERR_UNEXPECTED_TYPE, \
"expected '"FMT_str"' of type '"FMT_str"', but got '"FMT_str"'", \
str_unwrap(KEY), str_unwrap(t_expected_s), str_unwrap(t_got_s)); \
} \
Result(TomlTable*) TomlTable_get_table(const TomlTable* self, str key)
{
Deferral(1);
TomlValue* v = TomlTable_get(self, key);
try_assert_value_found(v, key);
try_assert_value_type(v, key, TLIBTOML_TABLE);
Return RESULT_VALUE(p, v->table);
}
Result(TomlArray*) TomlTable_get_array(const TomlTable* self, str key)
{
Deferral(1);
TomlValue* v = TomlTable_get(self, key);
try_assert_value_found(v, key);
try_assert_value_type(v, key, TLIBTOML_ARRAY);
Return RESULT_VALUE(p, v->array);
}
Result(str*) TomlTable_get_str(const TomlTable* self, str key)
{
Deferral(1);
TomlValue* v = TomlTable_get(self, key);
try_assert_value_found(v, key);
try_assert_value_type(v, key, TLIBTOML_STRING);
Return RESULT_VALUE(p, v->s);
}
Result(i64) TomlTable_get_integer(const TomlTable* self, str key)
{
Deferral(1);
TomlValue* v = TomlTable_get(self, key);
try_assert_value_found(v, key);
try_assert_value_type(v, key, TLIBTOML_INTEGER);
Return RESULT_VALUE(i, v->i);
}
Result(f64) TomlTable_get_float(const TomlTable* self, str key)
{
Deferral(1);
TomlValue* v = TomlTable_get(self, key);
try_assert_value_found(v, key);
try_assert_value_type(v, key, TLIBTOML_FLOAT);
Return RESULT_VALUE(f, v->f);
}
Result(TomlDateTime*) TomlTable_get_datetime(const TomlTable* self, str key)
{
Deferral(1);
TomlValue* v = TomlTable_get(self, key);
try_assert_value_found(v, key);
try_assert_value_type(v, key, TLIBTOML_DATETIME);
Return RESULT_VALUE(p, v->dt);
}
Result(bool) TomlTable_get_bool(const TomlTable* self, str key)
{
Deferral(1);
TomlValue* v = TomlTable_get(self, key);
try_assert_value_found(v, key);
try_assert_value_type(v, key, TLIBTOML_BOOLEAN);
Return RESULT_VALUE(i, v->b);
}

139
src/TomlValue.c Normal file
View File

@@ -0,0 +1,139 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "toml_internal.h"
Array_declare(str);
static Array(str) _TomlType_str_array = ARRAY(str, {
STR("INVALID_TYPE"),
STR("TABLE"),
STR("ARRAY"),
STR("STRING"),
STR("INTEGER"),
STR("FLOAT"),
STR("DATETIME"),
STR("BOOLEAN"),
});
str TomlType_toStr(TomlType t){
if((u32)t >= _TomlType_str_array.len)
return STR("!! ERROR: INVALID TomlType !!");
return _TomlType_str_array.data[t];
}
TomlValue TomlValue_new(TomlType type)
{
TomlValue value = {0};
value.type = type;
switch (type) {
default:
assert(false && "invalid type");
break;
case TLIBTOML_TABLE:
value.table = NULL;
break;
case TLIBTOML_ARRAY:
value.array = NULL;
break;
case TLIBTOML_STRING:
value.s = NULL;
break;
case TLIBTOML_INTEGER:
value.i = 0;
break;
case TLIBTOML_FLOAT:
value.f = 0.0;
break;
case TLIBTOML_BOOLEAN:
value.b = false;
break;
case TLIBTOML_DATETIME:
value.dt = (TomlDateTime*)malloc(sizeof(TomlDateTime));
memset(value.dt, 0, sizeof(TomlDateTime));
break;
}
return value;
}
TomlValue TomlValue_copy_str(str s)
{
return TomlValue_move_str(str_copy(s));
}
TomlValue TomlValue_move_str(str s){
TomlValue value = {0};
value.s = (str*)malloc(sizeof(str));
*value.s = s;
value.type = TLIBTOML_STRING;
return value;
}
TomlValue TomlValue_new_table(void)
{
TomlValue value = {0};
value.table = TomlTable_new();
value.type = TLIBTOML_TABLE;
return value;
}
TomlValue TomlValue_new_array(void)
{
TomlValue value = {0};
value.array = TomlArray_new();
value.type = TLIBTOML_ARRAY;
return value;
}
TomlValue TomlValue_new_integer(i64 integer)
{
TomlValue value = {0};
value.i = integer;
value.type = TLIBTOML_INTEGER;
return value;
}
TomlValue TomlValue_new_float(f64 float_)
{
TomlValue value = {0};
value.f = float_;
value.type = TLIBTOML_FLOAT;
return value;
}
TomlValue TomlValue_new_datetime(void)
{
return TomlValue_new(TLIBTOML_BOOLEAN);
}
TomlValue TomlValue_new_bool(bool b)
{
TomlValue value = {0};
value.b = b;
value.type = TLIBTOML_BOOLEAN;
return value;
}
void TomlValue_destroy(TomlValue* self)
{
if (!self)
return;
switch (self->type) {
case TLIBTOML_STRING:
str_free(self->s);
break;
case TLIBTOML_TABLE:
TomlTable_free(self->table);
break;
case TLIBTOML_ARRAY:
TomlArray_free(self->array);
break;
case TLIBTOML_DATETIME:
free(self->dt);
break;
default:
break;
}
}

15
src/tlibtoml.c Normal file
View File

@@ -0,0 +1,15 @@
#include "tlibtoml.h"
ErrorCodePage_define(TLIBTOML);
Result(void) tlibtoml_init(){
Deferral(8);
ErrorCodePage_register(TLIBTOML);
Return RESULT_VOID;
}
void tlibtoml_deinit(){
}

1786
src/toml.c

File diff suppressed because it is too large Load Diff

55
src/toml_internal.h Normal file
View File

@@ -0,0 +1,55 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
#include "tlibtoml.h"
#include "tlibc/string/StringBuilder.h"
#include <assert.h>
#include <ctype.h>
typedef struct _TomlParser {
cstr begin;
cstr end;
cstr ptr;
i32 lineno;
i32 colno;
cstr filename;
} TomlParser;
TomlParser* toml_parser_new(str s, cstr filename);
void toml_parser_free(TomlParser* self);
void toml_move_next(TomlParser* self);
void toml_next_n(TomlParser* self, i32 n);
u32 toml_hex_char_to_int(char ch);
Result(void) toml_encode_unicode_scalar(StringBuilder* sb_ptr, TomlParser* parser, i32 n);
Result(void) toml_parse_bare_key(TomlParser* self, str* out_str);
Result(void) toml_parse_basic_string(TomlParser* self, str* out_str);
Result(void) toml_parse_literal_string(TomlParser* self, str* out_str);
Result(void) toml_parse_basic_string_value(TomlParser* self, TomlValue* out_value);
Result(void) toml_parse_literal_string_value(TomlParser* self, TomlValue* out_value);
Result(void) toml_parse_multi_line_basic_string(TomlParser* self, TomlValue* out_value);
Result(void) toml_parse_multi_line_literal_string(TomlParser* self, TomlValue* out_value);
Result(void) toml_parse_datetime(str s, TomlValue* out_value);
Result(void) toml_parse_int_or_float_or_time(TomlParser* self, TomlValue* out_value);
Result(void) toml_parse_bool(TomlParser* self, TomlValue* out_value);
Result(void) toml_parse_value(TomlParser* self, TomlValue* out_value);
Result(void) toml_parse_array(TomlParser* self, TomlValue* out_value);
Result(void) toml_parse_inline_table(TomlParser* self, TomlValue* out_value);
Result(void) toml_parse_table(TomlParser* self, TomlTable* target_table);
Result(void) toml_parse_key_value(TomlParser* self, TomlTable* target_table);
Result(TomlTable*) toml_walk_table_path(TomlParser* parser, TomlTable* target_table,
TomlArray* key_path, bool is_array, bool create_if_not_exist);
Result(TomlTable*) toml_parse(TomlParser* self);
#ifdef __cplusplus
}
#endif

42
src/toml_load.c Normal file
View File

@@ -0,0 +1,42 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "toml_internal.h"
#include "tlibc/filesystem.h"
Result(TomlTable*) toml_load_str_filename(str s, cstr filename)
{
Deferral(1);
TomlParser* parser = toml_parser_new(s, filename);
Defer(toml_parser_free(parser));
try(TomlTable* table, p, toml_parse(parser));
Return RESULT_VALUE(p, table);
}
Result(TomlTable*) toml_load_file_filename(FILE* file, cstr filename)
{
Deferral(1);
str file_content;
try_void(file_readWholeText(file, &file_content));
Defer(str_destroy(file_content));
try(TomlTable* table, p, toml_load_str_filename(file_content, filename));
Return RESULT_VALUE(p, table);
}
Result(TomlTable*) toml_load_filename(cstr filename)
{
Deferral(1);
try(FILE* f, p, file_open(filename, FO_ReadExisting));
Defer(file_close(f));
try(TomlTable* table, p, toml_load_file_filename(f, filename));
Return RESULT_VALUE(p, table);
}

View File

@@ -0,0 +1,45 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "toml_internal.h"
Result(TomlTable*) toml_parse(TomlParser* self)
{
Deferral(1);
TomlTable* table = TomlTable_new();
bool success = false;
Defer(if(!success) TomlTable_free(table));
while (self->ptr < self->end) {
char ch = *self->ptr;
while (self->ptr < self->end && isspace(ch)) {
toml_move_next(self);
ch = *self->ptr;
}
if (ch == '#') {
do {
toml_move_next(self);
ch = *self->ptr;
} while (self->ptr < self->end && ch != '\n');
toml_move_next(self);
} else if (ch == '[') {
toml_move_next(self);
try_void(toml_parse_table(self, table));
} else if (isalnum(ch) || ch == '_' || ch == '-') {
try_void(toml_parse_key_value(self, table));
} else if (ch == ' ' || ch == '\t' || ch == '\r') {
do {
toml_move_next(self);
ch = *self->ptr;
} while (ch == ' ' || ch == '\t' || ch == '\r');
} else if (ch == '\n') {
toml_move_next(self);
}
}
success = true;
Return RESULT_VALUE(p, table);
}

View File

@@ -0,0 +1,58 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "toml_internal.h"
Result(void) toml_parse_array(TomlParser* self, TomlValue* out_value)
{
Deferral(1);
TomlValue array_value = TomlValue_new_array();
bool success = false;
Defer(if(!success) TomlValue_destroy(&array_value));
while (self->ptr < self->end) {
if (isspace(*self->ptr)) {
while (self->ptr < self->end && isspace(*self->ptr)) {
toml_move_next(self);
}
} else if (*self->ptr == '#') {
do {
toml_move_next(self);
} while (self->ptr < self->end &&* self->ptr != '\n');
toml_move_next(self);
} else if (*self->ptr == '\n') {
toml_move_next(self);
} else if (*self->ptr == ']') {
toml_move_next(self);
break;
} else {
TomlValue value;
try_void(toml_parse_value(self, &value));
TomlArray_append(array_value.array, value);
while (self->ptr < self->end) {
if (isspace(*self->ptr)) {
do {
toml_move_next(self);
} while (self->ptr < self->end && isspace(*self->ptr));
} else if (*self->ptr == '#') {
do {
toml_move_next(self);
} while (self->ptr < self->end &&* self->ptr != '\n');
} else {
break;
}
}
if (self->ptr < self->end &&* self->ptr == ',') {
toml_move_next(self);
}
}
}
success = true;
*out_value = array_value;
Return RESULT_VOID;
}

View File

@@ -0,0 +1,26 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "toml_internal.h"
Result(void) toml_parse_bare_key(TomlParser* self, str* s_out)
{
Deferral(1);
cstr s = self->ptr;
u64 len = 0;
while (self->ptr < self->end) {
char ch = *self->ptr;
if (!(isalnum(ch) || ch == '_' || ch == '-'))
break;
len++;
toml_move_next(self);
}
*s_out = str_copy(str_construct((void*)s, len, false));
Return RESULT_VOID;
}

View File

@@ -0,0 +1,71 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "toml_internal.h"
Result(void) toml_parse_basic_string(TomlParser* self, str* out_str)
{
Deferral(1);
StringBuilder sb = StringBuilder_alloc(32);
bool success = false;
Defer(if(!success) StringBuilder_destroy(&sb));
while (self->ptr < self->end &&* self->ptr != '\"' &&* self->ptr != '\n') {
char ch1 = *self->ptr;
if (ch1 == '\\') {
if (self->ptr >= self->end) break;
toml_move_next(self);
char ch2 = *self->ptr;
if (ch2 == '\"') {
StringBuilder_append_char(&sb, '\"');
toml_move_next(self);
} else if (ch2 == 'b') {
StringBuilder_append_char(&sb, '\b');
toml_move_next(self);
} else if (ch2 == 't') {
StringBuilder_append_char(&sb, '\t');
toml_move_next(self);
} else if (ch2 == 'n') {
StringBuilder_append_char(&sb, '\n');
toml_move_next(self);
} else if (ch2 == 'f') {
StringBuilder_append_char(&sb, '\f');
toml_move_next(self);
} else if (ch2 == 'r') {
StringBuilder_append_char(&sb, '\r');
toml_move_next(self);
} else if (ch2 == '\\') {
StringBuilder_append_char(&sb, '\\');
toml_move_next(self);
} else if (ch2 == 'u') {
toml_move_next(self);
try_void(toml_encode_unicode_scalar(&sb, self, 4));
} else if (ch2 == 'U') {
toml_move_next(self);
try_void(toml_encode_unicode_scalar(&sb, self, 8));
} else {
Return RESULT_ERROR_CODE_FMT(TLIBTOML, TLIBTOML_ERR_SYNTAX,
"%s:%d:%d: invalid escape character",
self->filename, self->lineno, self->colno);
}
} else {
StringBuilder_append_char(&sb, ch1);
toml_move_next(self);
}
}
if (self->ptr >= self->end ||* self->ptr != '\"' ||* self->ptr == '\n') {
Return RESULT_ERROR_CODE_FMT(TLIBTOML, TLIBTOML_ERR_SYNTAX,
"%s:%d:%d: unterminated basic string",
self->filename, self->lineno, self->colno);
}
toml_move_next(self);
*out_str = StringBuilder_getStr(&sb);
success = true;
Return RESULT_VOID;
}

View File

@@ -0,0 +1,16 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "toml_internal.h"
Result(void) toml_parse_basic_string_value(TomlParser* self, TomlValue* out_value)
{
Deferral(1);
str s;
try_void(toml_parse_basic_string(self, &s));
*out_value = TomlValue_move_str(s);
Return RESULT_VOID;
}

View File

@@ -0,0 +1,44 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "toml_internal.h"
static bool is_value_end(cstr expected_value_end, cstr input_end){
if(expected_value_end == input_end)
return true;
char next_ch = *expected_value_end;
return isspace(next_ch) || next_ch == ',' || next_ch == ']' || next_ch == '}';
}
Result(void) toml_parse_bool(TomlParser* self, TomlValue* out_value)
{
Deferral(1);
cstr val_end = self->ptr + 4;
if(val_end <= self->end && strncmp(self->ptr, "true", 4) == 0)
{
if(is_value_end(val_end, self->end))
{
toml_next_n(self, 4);
*out_value = TomlValue_new_bool(true);
Return RESULT_VOID;
}
}
val_end = self->ptr + 5;
if(val_end <= self->end && strncmp(self->ptr, "false", 5) == 0)
{
if(is_value_end(val_end, self->end))
{
toml_next_n(self, 5);
*out_value = TomlValue_new_bool(false);
Return RESULT_VOID;
}
}
Return RESULT_ERROR_CODE_FMT(TLIBTOML, TLIBTOML_ERR_SYNTAX,
"%s:%d:%d: value of unknown type",
self->filename, self->lineno, self->colno);
}

View File

@@ -0,0 +1,16 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "toml_internal.h"
Result(void) toml_parse_datetime(str s, TomlValue* out_value)
{
Deferral(1);
(void)s;
//TODO: parse datetime
try_assert(false && "DateTime parsing is not implemented");
TomlValue value = TomlValue_new(TLIBTOML_DATETIME);
*out_value = value;
Return RESULT_VOID;
}

View File

@@ -0,0 +1,92 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "toml_internal.h"
Result(void) toml_parse_inline_table(TomlParser* self, TomlValue* out_value)
{
Deferral(1);
TomlValue table_value = TomlValue_new_table();
bool success = false;
Defer(if(!success) TomlValue_destroy(&table_value));
while (self->ptr < self->end) {
char ch = *self->ptr;
while (self->ptr < self->end && (ch == ' ' || ch == '\t')) {
toml_move_next(self);
ch = *self->ptr;
}
str key;
if (isalnum(ch) || ch == '_') {
try_void(toml_parse_bare_key(self, &key));
} else if (ch == '\"') {
toml_move_next(self);
try_void(toml_parse_basic_string(self, &key));
} else if (ch == '\'') {
toml_move_next(self);
try_void(toml_parse_literal_string(self, &key));
} else if (ch == '}') {
break;
} else {
Return RESULT_ERROR_CODE_FMT(TLIBTOML, TLIBTOML_ERR_SYNTAX,
"%s:%d:%d: unexpected token",
self->filename, self->lineno, self->colno);
}
ch = *self->ptr;
while (self->ptr < self->end && (ch == ' ' || ch == '\t')) {
toml_move_next(self);
ch = *self->ptr;
}
if (self->ptr == self->end) {
Return RESULT_ERROR_CODE_FMT(TLIBTOML, TLIBTOML_ERR_SYNTAX,
"%s:%d:%d: unterminated key value pair",
self->filename, self->lineno, self->colno);
}
if (ch != '=') {
Return RESULT_ERROR_CODE_FMT(TLIBTOML, TLIBTOML_ERR_SYNTAX,
"%s:%d:%d: unexpected token",
self->filename, self->lineno, self->colno);
}
toml_move_next(self);
ch = *self->ptr;
while (self->ptr < self->end && (ch == ' ' || ch == '\t')) {
toml_move_next(self);
ch = *self->ptr;
}
if (self->ptr == self->end) {
Return RESULT_ERROR_CODE_FMT(TLIBTOML, TLIBTOML_ERR_SYNTAX,
"%s:%d:%d: unterminated key value pair",
self->filename, self->lineno, self->colno);
}
TomlValue value;
try_void(toml_parse_value(self, &value));
TomlTable_set(table_value.table, key, value);
str_destroy(key);
while (self->ptr < self->end && (*self->ptr == ' ' ||* self->ptr == '\t')) {
toml_move_next(self);
}
if (*self->ptr == ',') {
toml_move_next(self);
} else if (*self->ptr == '}') {
toml_move_next(self);
break;
}
}
success = true;
*out_value = table_value;
Return RESULT_VOID;
}

View File

@@ -0,0 +1,132 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "toml_internal.h"
Result(void) toml_parse_int_or_float_or_time(TomlParser* self, TomlValue* out_value)
{
Deferral(1);
StringBuilder sb = StringBuilder_alloc(32);
Defer(StringBuilder_destroy(&sb));
TomlValue value = {0};
char type = 'i';
i32 base = 10;
// Determine nan and inf type as float, as we cannot determine by dot.
// But do not strip it because we will append it to the string later
if (self->ptr + 3 <= self->end &&
(strncmp(self->ptr, "nan", 3) == 0 || strncmp(self->ptr, "inf", 3) == 0)) {
type = 'f';
}
if (self->ptr + 4 <= self->end &&
(strncmp(self->ptr, "+nan", 4) == 0 ||
strncmp(self->ptr, "-nan", 4) == 0 ||
strncmp(self->ptr, "+inf", 4) == 0 ||
strncmp(self->ptr, "-inf", 4) == 0))
{
type = 'f';
}
// If there is a base prefix, set the base and strip the prefix,
// because strtoll() do not recognize 0o and 0b
if (self->ptr + 2 <= self->end) {
if (strncmp(self->ptr, "0x", 2) == 0) {
base = 16;
toml_next_n(self, 2);
} else if (strncmp(self->ptr, "0o", 2) == 0) {
base = 8;
toml_next_n(self, 2);
} else if (strncmp(self->ptr, "0b", 2) == 0) {
base = 2;
toml_next_n(self, 2);
}
}
char last_char = 0;
i32 has_exp = false;
while (self->ptr < self->end) {
if (*self->ptr == '+' ||* self->ptr == '-') {
if (last_char == 0 || ((last_char == 'e' || last_char == 'E') && !has_exp)) {
if (last_char != 0) {
type = 'f';
has_exp = true;
}
StringBuilder_append_char(&sb,* self->ptr);
} else {
break;
}
} else if (isalnum(*self->ptr)) {
if ((*self->ptr == 'e' ||* self->ptr == 'E') && base == 10) {
type = 'f';
}
StringBuilder_append_char(&sb,* self->ptr);
} else if (*self->ptr == '.') {
if (type == 'i') {
type = 'f';
StringBuilder_append_char(&sb,* self->ptr);
} else {
Return RESULT_ERROR_CODE_FMT(TLIBTOML, TLIBTOML_ERR_SYNTAX,
"%s:%d:%d: invalid float",
self->filename, self->lineno, self->colno);
}
} else if (*self->ptr == '_') {
if (type == 't') {
Return RESULT_ERROR_CODE_FMT(TLIBTOML, TLIBTOML_ERR_SYNTAX,
"%s:%d:%d: invalid datetime",
self->filename, self->lineno, self->colno);
}
if (!isalnum(last_char)) {
Return RESULT_ERROR_CODE_FMT(TLIBTOML, TLIBTOML_ERR_SYNTAX,
"%s:%d:%d: invalid integer or float",
self->filename, self->lineno, self->colno);
}
} else if (*self->ptr == '-') {
type = 't';
StringBuilder_append_char(&sb,* self->ptr);
} else {
break;
}
last_char = *self->ptr;
toml_move_next(self);
}
if (last_char == '_') {
Return RESULT_ERROR_CODE_FMT(TLIBTOML, TLIBTOML_ERR_SYNTAX,
"%s:%d:%d: invalid integer or float or datetime",
self->filename, self->lineno, self->colno);
}
if (type == 'i') {
char* end = NULL;
char* start = StringBuilder_getStr(&sb).data;
i64 n = strtoll(start, &end, base);
if (end < start + sb.buffer.len) {
Return RESULT_ERROR_CODE_FMT(TLIBTOML, TLIBTOML_ERR_SYNTAX,
"%s:%d:%d: invalid integer",
self->filename, self->lineno, self->colno);
}
value = TomlValue_new_integer(n);
} else if (type == 'f') {
char* end = NULL;
char* start = StringBuilder_getStr(&sb).data;
f64 n = strtod(start, &end);
if (end < start + sb.buffer.len) {
Return RESULT_ERROR_CODE_FMT(TLIBTOML, TLIBTOML_ERR_SYNTAX,
"%s:%d:%d: invalid float",
self->filename, self->lineno, self->colno);
}
value = TomlValue_new_float(n);
} else if (type == 't') {
try_void(toml_parse_datetime(StringBuilder_getStr(&sb), &value));
}
*out_value = value;
Return RESULT_VOID;
}

View File

@@ -0,0 +1,111 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "toml_internal.h"
Result(void) toml_parse_key_value(TomlParser* self, TomlTable* target_table)
{
Deferral(1);
while (self->ptr < self->end) {
char ch;
ch = *self->ptr;
while (self->ptr < self->end && isspace(ch)) {
toml_move_next(self);
ch = *self->ptr;
}
if (self->ptr == self->end) break;
str key;
if (isalnum(ch) || ch == '_') {
try_void(toml_parse_bare_key(self, &key));
} else if (ch == '\"') {
toml_move_next(self);
try_void(toml_parse_basic_string(self, &key));
} else if (ch == '\'') {
toml_move_next(self);
try_void(toml_parse_literal_string(self, &key));
} else if (ch == '[') {
break;
} else if (ch == '#') {
do {
toml_move_next(self);
ch = *self->ptr;
} while (self->ptr < self->end && ch != '\n');
toml_move_next(self);
continue;
} else {
Return RESULT_ERROR_CODE_FMT(TLIBTOML, TLIBTOML_ERR_SYNTAX,
"%s:%d:%d: unexpected token",
self->filename, self->lineno, self->colno);
}
ch = *self->ptr;
while (self->ptr < self->end && (ch == ' ' || ch == '\t')) {
toml_move_next(self);
ch = *self->ptr;
}
if (self->ptr == self->end) {
Return RESULT_ERROR_CODE_FMT(TLIBTOML, TLIBTOML_ERR_SYNTAX,
"%s:%d:%d: unterminated key value pair",
self->filename, self->lineno, self->colno);
}
if (ch != '=') {
Return RESULT_ERROR_CODE_FMT(TLIBTOML, TLIBTOML_ERR_SYNTAX,
"%s:%d:%d: unexpected token",
self->filename, self->lineno, self->colno);
}
toml_move_next(self);
ch = *self->ptr;
while (self->ptr < self->end && (ch == ' ' || ch == '\t')) {
toml_move_next(self);
ch = *self->ptr;
}
if (self->ptr == self->end) {
Return RESULT_ERROR_CODE_FMT(TLIBTOML, TLIBTOML_ERR_SYNTAX,
"%s:%d:%d: unterminated key value pair",
self->filename, self->lineno, self->colno);
}
TomlValue value;
try_void(toml_parse_value(self, &value));
TomlTable_set(target_table, key, value);
str_destroy(key);
while (self->ptr < self->end && (*self->ptr == ' ' ||* self->ptr == '\t')) {
toml_move_next(self);
}
if (self->ptr == self->end)
break;
if (*self->ptr == '#') {
do {
toml_move_next(self);
} while (self->ptr < self->end &&* self->ptr != '\n');
}
if (*self->ptr == '\r') {
toml_move_next(self);
}
if (*self->ptr == '\n') {
toml_move_next(self);
} else {
Return RESULT_ERROR_CODE_FMT(TLIBTOML, TLIBTOML_ERR_SYNTAX,
"%s:%d:%d: new line expected",
self->filename, self->lineno, self->colno);
}
}
Return RESULT_VOID;
}

View File

@@ -0,0 +1,30 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "toml_internal.h"
Result(void) toml_parse_literal_string(TomlParser* self, str* out_str)
{
Deferral(1);
StringBuilder sb = StringBuilder_alloc(32);
bool success = false;
Defer(if(!success) StringBuilder_destroy(&sb));
while (self->ptr < self->end &&* self->ptr != '\'' &&* self->ptr != '\n') {
StringBuilder_append_char(&sb,* self->ptr);
toml_move_next(self);
}
if (self->ptr >= self->end ||* self->ptr != '\'' ||* self->ptr == '\n') {
Return RESULT_ERROR_CODE_FMT(TLIBTOML, TLIBTOML_ERR_SYNTAX,
"%s:%d:%d: unterminated literal string",
self->filename, self->lineno, self->colno);
}
toml_move_next(self);
*out_str = StringBuilder_getStr(&sb);
success = true;
Return RESULT_VOID;
}

View File

@@ -0,0 +1,16 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "toml_internal.h"
Result(void) toml_parse_literal_string_value(TomlParser* self, TomlValue* out_value)
{
Deferral(1);
str s;
try_void(toml_parse_literal_string(self, &s));
*out_value = TomlValue_move_str(s);
Return RESULT_VOID;
}

View File

@@ -0,0 +1,81 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "toml_internal.h"
Result(void) toml_parse_multi_line_basic_string(TomlParser* self, TomlValue* out_value)
{
Deferral(1);
StringBuilder sb = StringBuilder_alloc(32);
bool success = false;
Defer(if(!success) StringBuilder_destroy(&sb));
if (*self->ptr == '\n') {
toml_move_next(self);
}
while (self->ptr + 3 <= self->end && strncmp(self->ptr, "\"\"\"", 3) != 0) {
char ch1 = *self->ptr;
if (ch1 == '\\') {
if (self->ptr + 3 > self->end || strncmp(self->ptr, "\"\"\"", 3) == 0)
break;
toml_move_next(self);
char ch2 = *self->ptr;
if (ch2 == '\"') {
StringBuilder_append_char(&sb, '\"');
toml_move_next(self);
} else if (ch2 == 'b') {
StringBuilder_append_char(&sb, '\b');
toml_move_next(self);
} else if (ch2 == 't') {
StringBuilder_append_char(&sb, '\t');
toml_move_next(self);
} else if (ch2 == 'n') {
StringBuilder_append_char(&sb, '\n');
toml_move_next(self);
} else if (ch2 == 'f') {
StringBuilder_append_char(&sb, '\f');
toml_move_next(self);
} else if (ch2 == 'r') {
StringBuilder_append_char(&sb, '\r');
toml_move_next(self);
} else if (ch2 == '\\') {
StringBuilder_append_char(&sb, '\\');
toml_move_next(self);
} else if (ch2 == 'u') {
toml_move_next(self);
try_void(toml_encode_unicode_scalar(&sb, self, 4));
} else if (ch2 == 'U') {
toml_move_next(self);
try_void(toml_encode_unicode_scalar(&sb, self, 8));
} else if (ch2 == '\n') {
do {
toml_move_next(self);
} while (self->ptr + 3 <= self->end && isspace(*self->ptr));
} else {
Return RESULT_ERROR_CODE_FMT(TLIBTOML, TLIBTOML_ERR_SYNTAX,
"%s:%d:%d: invalid escape character",
self->filename, self->lineno, self->colno);
}
} else {
StringBuilder_append_char(&sb, ch1);
toml_move_next(self);
}
}
if (self->ptr + 3 > self->end || strncmp(self->ptr, "\"\"\"", 3) != 0) {
Return RESULT_ERROR_CODE_FMT(TLIBTOML, TLIBTOML_ERR_SYNTAX,
"%s:%d:%d: unterminated multi-line basic string",
self->filename, self->lineno, self->colno);
}
toml_next_n(self, 3);
*out_value = TomlValue_move_str(StringBuilder_getStr(&sb));
success = true;
Return RESULT_VOID;
}

View File

@@ -0,0 +1,34 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "toml_internal.h"
Result(void) toml_parse_multi_line_literal_string(TomlParser* self, TomlValue* out_value)
{
Deferral(1);
StringBuilder sb = StringBuilder_alloc(32);
bool success = false;
Defer(if(!success) StringBuilder_destroy(&sb));
if (*self->ptr == '\n') {
toml_move_next(self);
}
while (self->ptr + 3 <= self->end && strncmp(self->ptr, "\'\'\'", 3) != 0) {
StringBuilder_append_char(&sb,* self->ptr);
toml_move_next(self);
}
if (self->ptr + 3 > self->end || strncmp(self->ptr, "\'\'\'", 3) != 0) {
Return RESULT_ERROR_CODE_FMT(TLIBTOML, TLIBTOML_ERR_SYNTAX,
"%s:%d:%d: unterminated multi-line literal string",
self->filename, self->lineno, self->colno);
}
toml_next_n(self, 3);
*out_value = TomlValue_move_str(StringBuilder_getStr(&sb));
success = true;
Return RESULT_VOID;
}

View File

@@ -0,0 +1,87 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "toml_internal.h"
Result(void) toml_parse_table(TomlParser* self, TomlTable* target_table)
{
Deferral(1);
i32 is_array = false;
TomlTable* real_table = target_table;
TomlArray* key_path = TomlArray_new();
Defer(TomlArray_free(key_path));
if (self->ptr < self->end &&* self->ptr == '[') {
is_array = true;
toml_move_next(self);
}
while (1) {
if (*self->ptr == ' ' ||* self->ptr == '\t') {
do {
toml_move_next(self);
} while (*self->ptr <* self->end && (*self->ptr == ' ' ||* self->ptr == '\t'));
} else if (*self->ptr == ']') {
if (is_array) {
if (self->ptr + 2 <= self->end && strncmp(self->ptr, "]]", 2) == 0) {
toml_next_n(self, 2);
break;
}
} else {
toml_move_next(self);
break;
}
} else {
str key_part;
if (isalnum(*self->ptr) ||* self->ptr == '_') {
try_void(toml_parse_bare_key(self, &key_part));
} else if (*self->ptr == '\"') {
toml_move_next(self);
try_void(toml_parse_basic_string(self, &key_part));
} else if (*self->ptr == '\'') {
toml_move_next(self);
try_void(toml_parse_literal_string(self, &key_part));
} else {
Return RESULT_ERROR_CODE_FMT(TLIBTOML, TLIBTOML_ERR_SYNTAX,
"%s:%d:%d: unexpected token",
self->filename, self->lineno, self->colno);
}
TomlValue key_part_value = TomlValue_move_str(key_part);
TomlArray_append(key_path, key_part_value);
while (self->ptr < self->end &&
(*self->ptr == ' ' ||* self->ptr == '\t')) {
toml_move_next(self);
}
if (self->ptr < self->end &&* self->ptr == '.') {
toml_move_next(self);
}
}
}
if (key_path->len == 0) {
Return RESULT_ERROR_CODE_FMT(TLIBTOML, TLIBTOML_ERR_SYNTAX,
"%s:%d:%d: empty table name",
self->filename, self->lineno, self->colno);
}
while (self->ptr < self->end &&
(*self->ptr == ' ' ||* self->ptr == '\t' ||* self->ptr == '\r')) {
toml_move_next(self);
}
if (self->ptr < self->end &&* self->ptr != '\n') {
Return RESULT_ERROR_CODE_FMT(TLIBTOML, TLIBTOML_ERR_SYNTAX,
"%s:%d:%d: new line expected",
self->filename, self->lineno, self->colno);
}
try(real_table, p, toml_walk_table_path(self, target_table, key_path, is_array, true));
try_void(toml_parse_key_value(self, real_table));
Return RESULT_VOID;
}

View File

@@ -0,0 +1,44 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "toml_internal.h"
Result(void) toml_parse_value(TomlParser* self, TomlValue* out_value)
{
Deferral(1);
char ch = *self->ptr;
TomlValue value;
if (strncmp(self->ptr, "\"\"\"", 3) == 0) {
toml_next_n(self, 3);
try_void(toml_parse_multi_line_basic_string(self, &value));
} else if (strncmp(self->ptr, "\'\'\'", 3) == 0) {
toml_next_n(self, 3);
try_void(toml_parse_multi_line_literal_string(self, &value));
} else if (ch == '\"') {
toml_move_next(self);
try_void(toml_parse_basic_string_value(self, &value));
} else if (ch == '\'') {
toml_move_next(self);
try_void(toml_parse_literal_string_value(self, &value));
} else if (isdigit(ch) || ch == '+' || ch == '-' || ch == '.' || ch == 'n' || ch == 'i') {
try_void(toml_parse_int_or_float_or_time(self, &value));
} else if (ch == 't' || ch == 'f') {
try_void(toml_parse_bool(self, &value));
} else if (ch == '[') {
toml_move_next(self);
try_void(toml_parse_array(self, &value));
} else if (ch == '{') {
toml_move_next(self);
try_void(toml_parse_inline_table(self, &value));
} else {
Return RESULT_ERROR_CODE_FMT(TLIBTOML, TLIBTOML_ERR_SYNTAX,
"%s:%d:%d: unexpected token",
self->filename, self->lineno, self->colno);
}
*out_value = value;
Return RESULT_VOID;
}

View File

@@ -0,0 +1,84 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "toml_internal.h"
Result(Table*) toml_walk_table_path(TomlParser* parser, TomlTable* table,
TomlArray* key_path, bool is_array, bool create_if_not_exist)
{
Deferral(1);
TomlTable* real_table = table;
if (is_array) {
u64 i = 0;
for (; i < key_path->len - 1; i++) {
str part = *key_path->data[i].s;
TomlValue* t = TomlTable_get(real_table, part);
if (t == NULL) {
if (create_if_not_exist) {
TomlValue new_table_value = TomlValue_new_table();
TomlTable_set(real_table, part, new_table_value);
real_table = new_table_value.table;
} else {
Return RESULT_ERROR_CODE_FMT(TLIBTOML, TLIBTOML_ERR_SYNTAX,
"%s:%d:%d: not found key '" FMT_str "'",
parser->filename, parser->lineno, parser->colno, part.len, part.data);
}
} else {
real_table = t->table;
}
}
str part = *key_path->data[i].s;
TomlValue* t = TomlTable_get(real_table, part);
if (t == NULL) {
if (create_if_not_exist) {
TomlValue array_value = TomlValue_new_array();
TomlValue new_table_value = TomlValue_new_table();
TomlArray_append(array_value.array, new_table_value);
TomlTable_set(real_table, part, array_value);
real_table = new_table_value.table;
} else {
Return RESULT_ERROR_CODE_FMT(TLIBTOML, TLIBTOML_ERR_SYNTAX,
"%s:%d:%d: not found key '" FMT_str "'",
parser->filename, parser->lineno, parser->colno, part.len, part.data);
}
} else {
if (t->type != TLIBTOML_ARRAY) {
Return RESULT_ERROR_CODE_FMT(TLIBTOML, TLIBTOML_ERR_SYNTAX,
"%s:%d:%d: this key was not an array",
parser->filename, parser->lineno, parser->colno);
}
TomlValue new_table_value = TomlValue_new_table();
TomlArray_append(t->array, new_table_value);
real_table = new_table_value.table;
}
} else {
for (u64 i = 0; i < key_path->len; i++) {
str part = *key_path->data[i].s;
TomlValue* t = TomlTable_get(real_table, part);
if (t == NULL) {
if (create_if_not_exist) {
TomlValue new_table_value = TomlValue_new_table();
TomlTable_set(real_table, part, new_table_value);
real_table = new_table_value.table;
} else {
Return RESULT_ERROR_CODE_FMT(TLIBTOML, TLIBTOML_ERR_SYNTAX,
"%s:%d:%d: not found key '" FMT_str "'",
parser->filename, parser->lineno, parser->colno, part.len, part.data);
}
} else {
if (t->type == TLIBTOML_ARRAY) {
real_table = t->array->data[t->array->len - 1].table;
} else if (t->type == TLIBTOML_TABLE) {
real_table = t->table;
}
}
}
}
Return RESULT_VALUE(p, real_table);
}

140
src/toml_parser.c Normal file
View File

@@ -0,0 +1,140 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "toml_internal.h"
TomlParser* toml_parser_new(str s, cstr filename)
{
TomlParser* parser = (TomlParser*)malloc(sizeof(TomlParser));
parser->begin = s.data;
parser->end = s.data + s.len;
parser->ptr = s.data;
parser->lineno = 1;
parser->colno = 1;
parser->filename = filename;
return parser;
}
void toml_parser_free(TomlParser* self)
{
if (!self)
return;
free(self);
}
void toml_move_next(TomlParser* self)
{
if (self->ptr < self->end) {
if (*self->ptr == '\n') {
self->lineno++;
self->colno = 1;
} else {
self->colno++;
}
self->ptr++;
}
}
void toml_next_n(TomlParser* self, i32 n)
{
for (i32 i = 0; i < n; i++) {
toml_move_next(self);
}
}
u32 toml_hex_char_to_int(char ch)
{
assert(isxdigit(ch));
if (isdigit(ch)) {
return ch - '0';
} else if (islower(ch)) {
return ch - 'a' + 10;
} else if (isupper(ch)) {
return ch - 'A' + 10;
}
return 0;
}
Result(void) toml_encode_unicode_scalar(StringBuilder* sb_ptr, TomlParser* parser, i32 n)
{
Deferral(1);
u32 scalar = 0;
if (parser->ptr + n > parser->end) {
Return RESULT_ERROR_CODE_FMT(TLIBTOML, TLIBTOML_ERR_UNICODE,
"%s:%d:%d: invalid unicode scalar",
parser->filename, parser->lineno, parser->colno);
}
for (i32 i = 0; i < n; i++) {
char ch = *parser->ptr;
if (isxdigit(ch)) {
scalar = scalar * 16 + toml_hex_char_to_int(ch);
toml_move_next(parser);
} else {
Return RESULT_ERROR_CODE_FMT(TLIBTOML, TLIBTOML_ERR_UNICODE,
"%s:%d:%d: invalid unicode scalar",
parser->filename, parser->lineno, parser->colno);
}
}
if ((scalar >= 0xd800 && scalar <= 0xdfff) ||
(scalar >= 0xfffe && scalar <= 0xffff))
{
Return RESULT_ERROR_CODE_FMT(TLIBTOML, TLIBTOML_ERR_UNICODE,
"%s:%d:%d: invalid unicode scalar",
parser->filename, parser->lineno, parser->colno);
}
if (scalar <= 0x7f) {
StringBuilder_append_char(sb_ptr, (char)scalar);
Return RESULT_VOID;
}
if (scalar <= 0x7ff) {
StringBuilder_append_char(sb_ptr, (char)(0xc0 | (scalar >> 6)));
StringBuilder_append_char(sb_ptr, (char)(0x80 | (scalar & 0x3f)));
Return RESULT_VOID;
}
if (scalar <= 0xffff) {
StringBuilder_append_char(sb_ptr, (char)(0xe0 | (scalar >> 12)));
StringBuilder_append_char(sb_ptr, (char)(0x80 | ((scalar >> 6) & 0x3f)));
StringBuilder_append_char(sb_ptr, (char)(0x80 | (scalar & 0x3f)));
Return RESULT_VOID;
}
if (scalar <= 0x1fffff) {
StringBuilder_append_char(sb_ptr, (char)(0xf0 | (scalar >> 18)));
StringBuilder_append_char(sb_ptr, (char)(0x80 | ((scalar >> 12) & 0x3f)));
StringBuilder_append_char(sb_ptr, (char)(0x80 | ((scalar >> 6) & 0x3f)));
StringBuilder_append_char(sb_ptr, (char)(0x80 | (scalar & 0x3f)));
Return RESULT_VOID;
}
if (scalar <= 0x3ffffff) {
StringBuilder_append_char(sb_ptr, (char)(0xf8 | (scalar >> 24)));
StringBuilder_append_char(sb_ptr, (char)(0x80 | ((scalar >> 18) & 0x3f)));
StringBuilder_append_char(sb_ptr, (char)(0x80 | ((scalar >> 12) & 0x3f)));
StringBuilder_append_char(sb_ptr, (char)(0x80 | ((scalar >> 6) & 0x3f)));
StringBuilder_append_char(sb_ptr, (char)(0x80 | (scalar & 0x3f)));
Return RESULT_VOID;
}
if (scalar <= 0x7fffffff) {
StringBuilder_append_char(sb_ptr, (char)(0xfc | (scalar >> 30)));
StringBuilder_append_char(sb_ptr, (char)(0x80 | ((scalar >> 24) & 0x3f)));
StringBuilder_append_char(sb_ptr, (char)(0x80 | ((scalar >> 18) & 0x3f)));
StringBuilder_append_char(sb_ptr, (char)(0x80 | ((scalar >> 12) & 0x3f)));
StringBuilder_append_char(sb_ptr, (char)(0x80 | ((scalar >> 6) & 0x3f)));
StringBuilder_append_char(sb_ptr, (char)(0x80 | (scalar & 0x3f)));
Return RESULT_VOID;
}
Return RESULT_ERROR_CODE_FMT(TLIBTOML, TLIBTOML_ERR_UNICODE,
"%s:%d:%d: invalid unicode scalar",
parser->filename, parser->lineno, parser->colno);
}

View File

@@ -3,7 +3,8 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include <inttypes.h>
#include "tlibtoml/toml.h"
#include <assert.h>
#include "tlibtoml.h"
#ifndef PROJECT_SOURCE_DIR
#define PROJECT_SOURCE_DIR ".."
@@ -15,11 +16,11 @@ void print_value(const TomlValue *value);
void print_array(const TomlArray *array)
{
printf("[");
for (size_t i = 0; i < array->len; i++) {
for (u64 i = 0; i < array->len; i++) {
if (i > 0) {
printf(", ");
}
print_value(array->elements[i]);
print_value(&array->data[i]);
}
printf("]");
}
@@ -27,82 +28,75 @@ void print_array(const TomlArray *array)
void print_value(const TomlValue* value)
{
switch (value->type) {
case TOML_TABLE:
print_table(value->value.table);
default:
assert(false && "invalid type");
break;
case TOML_ARRAY:
print_array(value->value.array);
case TLIBTOML_TABLE:
print_table(value->table);
break;
case TOML_STRING:
printf("\"%s\"", value->value.string->str);
case TLIBTOML_ARRAY:
print_array(value->array);
break;
case TOML_INTEGER:
printf("%" PRId64, value->value.integer);
case TLIBTOML_STRING:
printf("'" FMT_str "'", value->s->len, value->s->data);
break;
case TOML_FLOAT:
printf("%f", value->value.float_);
case TLIBTOML_INTEGER:
printf("%" PRId64, value->i);
break;
case TOML_DATETIME:
case TLIBTOML_FLOAT:
printf("%f", value->f);
break;
case TLIBTOML_DATETIME:
printf("(datetime)");
break;
case TOML_BOOLEAN:
printf("%s", value->value.boolean ? "true" : "false");
case TLIBTOML_BOOLEAN:
printf("%s", value->b ? "true" : "false");
break;
}
}
void print_keyval(const TomlKeyValue *keyval)
void print_keyval(HashMapKeyValue* keyval)
{
printf("\"%s\": ", keyval->key->str);
print_value(keyval->value);
printf("\"%s\": ", keyval->key.data);
print_value(keyval->value_ptr);
}
void print_table(const TomlTable* table)
{
TomlTableIter it = toml_table_iter_new((TomlTable *)table);
HashMapIter it = HashMapIter_create(table);
printf("{");
size_t i = 0;
while (toml_table_iter_has_next(&it)) {
TomlKeyValue *keyval = toml_table_iter_get(&it);
if (i > 0) {
u64 i = 0;
HashMapKeyValue keyval;
while (HashMapIter_moveNext(&it)) {
assert(HashMapIter_getCurrent(&it, &keyval));
if (i > 0)
printf(", ");
}
print_keyval(keyval);
toml_table_iter_next(&it);
print_keyval(&keyval);
i++;
}
printf("}");
}
int test_run(const char *filename)
Result(void) test_run(cstr filename)
{
TomlTable *table = NULL;
int rc = 0;
table = toml_load_filename(filename);
if (table == NULL)
goto cleanup;
Deferral(1);
try(TomlTable* table, p, toml_load_filename(filename));
Defer(TomlTable_free(table));
print_table(table);
printf("\n");
cleanup:
toml_table_free(table);
if (toml_err()->code != TOML_OK) {
fprintf(stderr, "%s\n", toml_err()->message);
rc = (int)toml_err()->code;
}
toml_err_clear();
return rc;
Return RESULT_VOID;
}
int main(void)
i32 main(void)
{
static const char *const filenames[] = {
Deferral(32);
try_fatal_void(tlibc_init());
Defer(tlibc_deinit());
try_fatal_void(tlibtoml_init());
Defer(tlibtoml_deinit());
static cstr const filenames[] = {
/* should parse */
PROJECT_SOURCE_DIR "/tests/key-values.toml",
PROJECT_SOURCE_DIR "/tests/complex-structure.toml",
@@ -117,17 +111,19 @@ int main(void)
PROJECT_SOURCE_DIR "/tests/hard_example_unicode.toml"
};
int total_tests = sizeof(filenames) / sizeof(char *);
int num_passed = 0;
int num_failed = 0;
i32 total_tests = sizeof(filenames) / sizeof(char*);
i32 num_passed = 0;
i32 num_failed = 0;
for (int i = 0; i < total_tests; i++) {
int rc = test_run(filenames[i]);
if (rc == 0) {
for (i32 i = 0; i < total_tests; i++) {
ResultVar(void) r = test_run(filenames[i]);
if (!r.error) {
printf("test %d success\n", i);
num_passed++;
} else {
printf("test %d returned %d\n", i, rc);
str err_str = Error_toStr(r.error);
printf("%s\ntest %d failed\n", err_str.data, i);
str_destroy(err_str);
num_failed++;
}
}
@@ -135,5 +131,5 @@ int main(void)
printf("total %d tests, %d passed, %d failed\n",
total_tests, num_passed, num_failed);
return num_failed;
Return num_failed;
}

View File

@@ -5,9 +5,12 @@
DEP_WORKING_DIR="$DEPENDENCIES_DIR/tlibtoml"
user_config_path="project.config.user"
absolute_dep_dir=$(realpath "$DEPENDENCIES_DIR")
function setup_user_config(){
local user_config_path="project.config.user"
local absolute_dep_dir=$(realpath "$DEPENDENCIES_DIR")
# Set variable `DEPENDENCIES_DIR`` in `tlibtoml/project.config.user`
# to the directory where `tlibc`` is installed
file_copy_default_if_not_present "$user_config_path" "$user_config_path.default"
replace_var_value_in_script "$user_config_path" "DEPENDENCIES_DIR" "$absolute_dep_dir"
}