From de39a41da62c4b3820b4805ddb7c4970c36bc257 Mon Sep 17 00:00:00 2001 From: "Rafael G. Martins" Date: Sat, 18 Apr 2015 17:17:37 -0300 Subject: added loader, error handling and cli. tests needed --- src/error.c | 116 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 116 insertions(+) create mode 100644 src/error.c (limited to 'src/error.c') diff --git a/src/error.c b/src/error.c new file mode 100644 index 0000000..8475d66 --- /dev/null +++ b/src/error.c @@ -0,0 +1,116 @@ +/* + * blogc: A blog compiler. + * Copyright (C) 2015 Rafael G. Martins + * + * This program can be distributed under the terms of the BSD License. + * See the file COPYING. + */ + +#ifdef HAVE_CONFIG_H +#include +#endif /* HAVE_CONFIG_H */ + +#include +#include +#include +#include +#include "utils/utils.h" +#include "error.h" + + +blogc_error_t* +blogc_error_new(blogc_error_type_t type, const char *msg) +{ + blogc_error_t *err = malloc(sizeof(blogc_error_t)); + err->type = type; + err->msg = b_strdup(msg); + return err; +} + + +blogc_error_t* +blogc_error_new_printf(blogc_error_type_t type, const char *format, ...) +{ + va_list ap; + va_start(ap, format); + char *tmp = b_strdup_vprintf(format, ap); + va_end(ap); + blogc_error_t *rv = blogc_error_new(type, tmp); + free(tmp); + return rv; +} + + +blogc_error_t* +blogc_error_parser(blogc_error_type_t type, const char *src, size_t src_len, + size_t current, const char *format, ...) +{ + va_list ap; + va_start(ap, format); + char *msg = b_strdup_vprintf(format, ap); + va_end(ap); + + b_string_t *str = b_string_new(); + while (current < src_len) { + char c = src[current]; + + if (c == '\r' || c == '\n') + break; + + b_string_append_c(str, c); + + current++; + } + char *line = b_string_free(str, false); + + blogc_error_t *rv = NULL; + + if (strlen(line) == 0) // "near to" message isn't useful if line is empty + rv = blogc_error_new(type, msg); + else + rv = blogc_error_new_printf(type, + "%s\nError occurred near to \"%s\".", msg, line); + + free(msg); + free(line); + + return rv; +} + + +void +blogc_error_print(blogc_error_t *err) +{ + if (err == NULL) + return; + + char *tmp = NULL; + + switch(err->type) { + case BLOGC_ERROR_SOURCE_PARSER: + tmp = b_strdup("Source parser error"); + break; + case BLOGC_ERROR_TEMPLATE_PARSER: + tmp = b_strdup("Template parser error"); + break; + case BLOGC_ERROR_LOADER: + tmp = b_strdup("Loader error"); + break; + default: + tmp = b_strdup("Unknown error"); + } + + fprintf(stderr, "%s: %s\n", tmp, err->msg); + + free(tmp); +} + + +void +blogc_error_free(blogc_error_t *err) +{ + if (err == NULL) + return; + free(err->msg); + free(err); +} -- cgit v1.2.3-18-g5258