(FEA) More macros for Status

This commit is contained in:
William
2024-06-07 17:17:32 +08:00
parent 66c1d57188
commit 8775d75de8
14 changed files with 415 additions and 525 deletions

View File

@@ -4,9 +4,9 @@
Status Array_Create(Array *inst, int len, size_t size) Status Array_Create(Array *inst, int len, size_t size)
{ {
/* Skip unavailable inst and invalid param. */ /* Skip unavailable inst and invalid param. */
fails(inst, UnavailableInstance); fails(inst, apply(UnavailableInstance));
state((len < 0), InvalidArrayLength); state((len < 0), apply(InvalidArrayLength));
solve((!len), { inst->len = 0; inst->members = NULL; return NormalStatus; }) solve((!len), { inst->len = 0; inst->members = NULL; return apply(NormalStatus); })
inst->len = len; inst->len = len;
inst->members = calloc(len, sizeof(Var)); inst->members = calloc(len, sizeof(Var));
@@ -40,22 +40,22 @@ Status Array_Create(Array *inst, int len, size_t size)
/* Release array itself. */ /* Release array itself. */
free(inst->members); free(inst->members);
return InsufficientMemory; return apply(InsufficientMemory);
} }
return NormalStatus; return apply(NormalStatus);
} }
Status Array_CopyOf(Array *inst, Array *other) Status Array_CopyOf(Array *inst, Array *other)
{ {
// /* Skip unavailable inst and invalid param. */ // /* Skip unavailable inst and invalid param. */
// fails(inst, UnavailableInstance); // fails(inst, apply(UnavailableInstance));
// fails(other, error(InvalidParameter, "Given other was unavailable.")); // fails(other, error(InvalidParameter, "Given other was unavailable."));
// /* Assign value for len. */ // /* Assign value for len. */
// inst->len = other->len; // inst->len = other->len;
// if (inst->members == NULL) return NormalStatus; // if (inst->members == NULL) return apply(NormalStatus);
// match(RuntimeError, Array_Create(inst, other->len), "Failed on recreating " // match(RuntimeError, Array_Create(inst, other->len), "Failed on recreating "
// "array."); // "array.");
@@ -64,7 +64,7 @@ Status Array_CopyOf(Array *inst, Array *other)
// inst[i] = other[i]; // inst[i] = other[i];
// } // }
// return NormalStatus; // return apply(NormalStatus);
@@ -86,40 +86,41 @@ Status Array_CopyOf(Array *inst, Array *other)
Status Array_Delete(Array *inst) Status Array_Delete(Array *inst)
{ {
/* Skip unavailable inst and invalid param. */ /* Skip unavailable inst and invalid param. */
fails(inst, UnavailableInstance); fails(inst, apply(UnavailableInstance));
solve((inst->members == NULL), return NormalStatus); solve((inst->members == NULL), return apply(NormalStatus));
inst->len = 0; inst->len = 0;
free(inst->members); free(inst->members);
inst->members = NULL; inst->members = NULL;
return NormalStatus; return apply(NormalStatus);
} }
Status Array_GetIdx(Array *inst, Var *store, int index) Status Array_GetIdx(Array *inst, Var *store, int index)
{ {
/* Skip unavailable inst and invalid param. */ /* Skip unavailable inst and invalid param. */
fails(inst, UnavailableInstance); fails(inst, apply(UnavailableInstance));
fails(store, error(InvalidParameter, "Given reference to store was " fails(store,
"unavailable.")); apply(error(InvalidParameter, "Given reference to store was unavailable.")));
state((index < 0 || index >= inst->len), ArrayIndexOutOfBound); state((index < 0 || index >= inst->len), apply(ArrayIndexOutOfBound));
*store = inst->members[index]; *store = inst->members[index];
return NormalStatus; return apply(NormalStatus);
} }
Status Array_SetIdx(Array *inst, Var *source, int index) Status Array_SetIdx(Array *inst, Var *source, int index)
{ {
/* Skip unavailable inst and invalid param. */ /* Skip unavailable inst and invalid param. */
fails(inst, UnavailableInstance); fails(inst, apply(UnavailableInstance));
fails(source, error(InvalidParameter, "Given reference to source was " fails(source,
"unavailable.")); apply(
state((index < 0 || index >= inst->len), ArrayIndexOutOfBound); error(InvalidParameter, "Given reference to source was unavailable.")));
state((index < 0 || index >= inst->len), apply(ArrayIndexOutOfBound));
inst->members[index] = *source; inst->members[index] = *source;
return NormalStatus; return apply(NormalStatus);
} }
bool Array_Equals(Array *a, Array *b) bool Array_Equals(Array *a, Array *b)
@@ -141,14 +142,16 @@ bool Array_Equals(Array *a, Array *b)
Status ArrayUtils_Fill(Array *inst, Var *elem, int off, int len) Status ArrayUtils_Fill(Array *inst, Var *elem, int off, int len)
{ {
fails(inst, UnavailableInstance); fails(inst, apply(UnavailableInstance));
fails(elem, error(InvalidParameter, "Given reference to elem was unavailable.")); fails(elem,
state((off + len > inst->len) || (off < 0) || (len < 0), ArrayIndexOutOfBound); apply(error(InvalidParameter, "Given reference to elem was unavailable.")));
state((off + len > inst->len) || (off < 0) || (len < 0),
apply(ArrayIndexOutOfBound));
/* Copy elem into each specified members from inst with off and len. */ /* Copy elem into each specified members from inst with off and len. */
for (register int i = off; i < (off + len); i++) { for (register int i = off; i < (off + len); i++) {
inst->members[i] = *elem; inst->members[i] = *elem;
} }
return NormalStatus; return apply(NormalStatus);
} }

View File

@@ -2,7 +2,10 @@ cmake_minimum_required (VERSION 3.5)
project (Compound) project (Compound)
add_compile_options(-g -std=c99 -Wall -Wextra -Wformat)
set(SHARED_SOURCE set(SHARED_SOURCE
MemMan/src/memman.c
Status/src/status.c Status/src/status.c
Utils/src/utils.c Utils/src/utils.c
Var/src/var.c Var/src/var.c
@@ -12,7 +15,6 @@ set(LIBCOMPOUND_SOURCE ${SHARED_SOURCE})
add_library(compound SHARED ${LIBCOMPOUND_SOURCE}) add_library(compound SHARED ${LIBCOMPOUND_SOURCE})
add_compile_options(-g -std=c99 -Wall -Wextra -Wformat)
LINK_LIBRARIES(m) LINK_LIBRARIES(m)
# add_executable(CompoundTest test.c # add_executable(CompoundTest test.c

View File

@@ -2,7 +2,7 @@
Status Memory_Create(Memory *inst, size_t size) Status Memory_Create(Memory *inst, size_t size)
{ {
fails(inst, UnavailableInstance); fails(inst, apply(UnavailableInstance));
*inst = (Memory) { *inst = (Memory) {
.addr = NULL, .addr = NULL,
@@ -11,57 +11,58 @@ Status Memory_Create(Memory *inst, size_t size)
.alive = false .alive = false
}; };
return NormalStatus; return apply(NormalStatus);
} }
Status Memory_Allocate(Memory *inst) Status Memory_Allocate(Memory *inst)
{ {
fails(inst, UnavailableInstance); fails(inst, apply(UnavailableInstance));
state(inst->alive, InstanceStillAlive); state(inst->alive, apply(InstanceStillAlive));
/* When failed on allocating. */ /* When failed on allocating. */
state(!(inst->addr = malloc(inst->size)), InsufficientMemory); state(!(inst->addr = malloc(inst->size)), apply(InsufficientMemory));
inst->alive = true; inst->alive = true;
return NormalStatus; return apply(NormalStatus);
} }
Status Memory_Reallocate(Memory *inst, size_t size) Status Memory_Reallocate(Memory *inst, size_t size)
{ {
fails(inst, UnavailableBuffer); fails(inst, apply(UnavailableBuffer));
state(!inst->alive, InstanceNotAlive); state(!inst->alive, apply(InstanceNotAlive));
/* When failed on reallocating. */ /* When failed on reallocating. */
state(!(inst->addr = realloc(inst->addr, size)), state(!(inst->addr = realloc(inst->addr, size)),
error(InsufficientMemory, "Unsuccessful reallocation was received.")) apply(error(InsufficientMemory, "Unsuccessful reallocation was received.")));
return NormalStatus; return apply(NormalStatus);
} }
Status Memory_Release(Memory *inst) Status Memory_Release(Memory *inst)
{ {
fails(inst, UnavailableInstance); fails(inst, apply(UnavailableInstance));
state(!inst->alive, error(InstanceNotAlive, "Cannot release a non-alive " state(!inst->alive,
"instance.")); apply(error(InstanceNotAlive, "Cannot release a non-alive instance.")));
free(inst->addr); free(inst->addr);
inst->alive = false; inst->alive = false;
return NormalStatus; return apply(NormalStatus);
} }
Status Memory_Delete(Memory *inst) Status Memory_Delete(Memory *inst)
{ {
fails(inst, UnavailableInstance); fails(inst, apply(UnavailableInstance));
state(inst->alive, error(InstanceStillAlive, "Cannot deinitialise a instance " state(inst->alive,
"still alive.")); apply(
error(InstanceStillAlive, "Cannot deinitialise a instance still alive.")));
inst->addr = NULL; inst->addr = NULL;
inst->priority = 0; inst->priority = 0;
inst->size = 0; inst->size = 0;
inst = NULL; inst = NULL;
return NormalStatus; return apply(NormalStatus);
} }
bool Memory_Equals(Memory *inst, Memory *other) bool Memory_Equals(Memory *inst, Memory *other)

View File

@@ -21,6 +21,8 @@ Status Stack_Create(Stack *inst, int len)
// }; // };
// } // }
// } // }
return apply(NormalStatus);
} }
Status Stack_CopyOf(Stack *inst, Stack *other); Status Stack_CopyOf(Stack *inst, Stack *other);
Status Stack_Push(Stack *inst, Var *item); Status Stack_Push(Stack *inst, Var *item);

View File

@@ -63,6 +63,16 @@ typedef struct _Status {
struct _Status *prev; struct _Status *prev;
} Status; } Status;
# define DEFSTATUS(i, v, d, c, p)\
static const Status i = {\
.identity = nameof(i),\
.value = v,\
.description = d,\
.characteristic = c,\
.loc = __GLOBAL__,\
.prev = (Status *)p\
}
/* /*
{value "description" characteristic prev} {value "description" characteristic prev}
@@ -123,7 +133,7 @@ typedef struct {
char *initiator; char *initiator;
time_t time; time_t time;
ReportSendingPriority priority; ReportSendingPriority priority;
ReportSendingTaskStatus task_status; ReportSendingTaskStatus taskprint_status;
FILE *dest; // The destination where the report is sending to. FILE *dest; // The destination where the report is sending to.
} Report; } Report;
@@ -256,310 +266,139 @@ Status ReportSenderManager_RemoveTask(ReportSendingManager *inst,
// ---------------------ELEMENTARY------------------------- // ---------------------ELEMENTARY-------------------------
/* DEFSTATUS(UnknownStatus, -1, "An unknown status.", STATUS_UNKNOWN, NULL);
typedef struct _Status { DEFSTATUS(NormalStatus, 0, "A normal status.", STATUS_NORMAL, NULL);
char *identity; DEFSTATUS(ErrorStatus, 1, "An error status.", STATUS_ERROR, NULL);
int value;
char *description;
int characteristic;
Location loc;
struct _Status *prev;
} Status;
*/
static const Status UnknownStatus = {
.identity = nameof(UnknownStatus),
.value = -1,
.description = "An unknown status.",
.characteristic = STATUS_UNKNOWN,
.loc = __GLOBAL__,
.prev = NULL
};
static const Status NormalStatus = {
.identity = nameof(NormalStatus),
.value = 0,
.description = "A normal status.",
.characteristic = STATUS_NORMAL,
.loc = __GLOBAL__,
.prev = NULL
};
static const Status ErrorStatus = {
.identity = nameof(ErrorStatus),
.value = 1,
.description = "An error status.",
.characteristic = STATUS_ERROR,
.loc = __GLOBAL__,
.prev = NULL
};
// ----------------------EXTENDED-------------------------- // ----------------------EXTENDED--------------------------
static const Status MemoryViolation = (Status){ DEFSTATUS(MemoryViolation, 1,
.identity = nameof(MemoryViolation), "Illegal access on certain memory address.",
.value = 1, STATUS_ERROR, &ErrorStatus);
.description = "Illegal access on certain memory address.",
.characteristic = STATUS_ERROR,
.loc = __GLOBAL__,
.prev = (Status *)&ErrorStatus
};
static const Status NullPointerAccounted = (Status){ DEFSTATUS(NullPointerAccounted, 1,
.identity = nameof(NullPointerAccounted), "An involving null pointer was not accepted.",
.value = 1, STATUS_ERROR, &MemoryViolation);
.description = "An involving null pointer was not accepted.",
.characteristic = STATUS_ERROR,
.loc = __GLOBAL__,
.prev = (Status *)&MemoryViolation
};
static const Status InvalidObject = (Status){ DEFSTATUS(InvalidObject, 1,
.identity = nameof(InvalidObject), "An invalid object was presented.",
.value = 1, STATUS_ERROR, &ErrorStatus);
.description = "An invalid object was presented.",
.characteristic = STATUS_ERROR,
.loc = __GLOBAL__,
.prev = (Status *)&ErrorStatus
};
static const Status UnavailableObject = (Status){ DEFSTATUS(UnavailableObject, 1,
.identity = nameof(UnavailableObject), "An unavailable object was presented.",
.value = 1, STATUS_ERROR, &ErrorStatus);
.description = "An unavailable object was presented.",
.characteristic = STATUS_ERROR,
.loc = __GLOBAL__,
.prev = (Status *)&ErrorStatus
};
static const Status InstanceStillAlive = (Status){ DEFSTATUS(InstanceStillAlive, 1,
.identity = nameof(InstanceStillAlive), "Given instance was yet alive.",
.value = 1, STATUS_ERROR, &ErrorStatus);
.description = "Given instance was yet alive.",
.characteristic = STATUS_ERROR,
.loc = __GLOBAL__,
.prev = (Status *)&ErrorStatus
};
static const Status InstanceNotAlive = (Status){ DEFSTATUS(InstanceNotAlive, 1,
.identity = nameof(InstanceNotAlive), "Given instance for reallocation was not alive.",
.value = 1, STATUS_ERROR, &ErrorStatus);
.description = "Given instance for reallocation was not alive.",
.characteristic = STATUS_ERROR,
.loc = __GLOBAL__,
.prev = (Status *)&ErrorStatus
};
static const Status InvalidParameter = (Status){ DEFSTATUS(InvalidParameter, 1,
.identity = nameof(InvalidParameter), "An invalid parameter was presented.",
.value = 1, STATUS_ERROR, &InvalidObject);
.description = "An invalid parameter was presented.",
.characteristic = STATUS_ERROR,
.loc = __GLOBAL__,
.prev = (Status *)&InvalidObject
};
static const Status InsufficientMemory = (Status){ DEFSTATUS(InsufficientMemory, 1,
.identity = nameof(InsufficientMemory), "Not enough room for further memory allocations.",
.value = 1, STATUS_ERROR, &ErrorStatus);
.description = "Not enough room for further memory allocations.",
.characteristic = STATUS_ERROR,
.loc = __GLOBAL__,
.prev = (Status *)&ErrorStatus
};
static const Status ArithmeticError = (Status){ DEFSTATUS(ArithmeticError, 1,
.identity = nameof(ArithmeticError), "An arithmetic error occurred.",
.value = 1, STATUS_ERROR, &ErrorStatus);
.description = "An arithmetic error occurred.",
.characteristic = STATUS_ERROR,
.loc = __GLOBAL__,
.prev = (Status *)&ErrorStatus
};
static const Status IntegerOverFlow = (Status){ DEFSTATUS(IntegerOverFlow, 1,
.identity = nameof(IntegerOverFlow), "An integer had overflowed.",
.value = 1, STATUS_ERROR, &ArithmeticError);
.description = "An integer had overflowed.",
.characteristic = STATUS_ERROR,
.loc = __GLOBAL__,
.prev = (Status *)&ArithmeticError
};
static const Status RuntimeError = (Status){ DEFSTATUS(RuntimeError, 1,
.identity = nameof(RuntimeError), "A runtime error occurred.",
.value = 1, STATUS_ERROR, &ErrorStatus);
.description = "A runtime error occurred.",
.characteristic = STATUS_ERROR,
.loc = __GLOBAL__,
.prev = (Status *)&ErrorStatus
};
static const Status ArrayLengthError = (Status){ DEFSTATUS(ArrayLengthError, 1,
.identity = nameof(ArrayLengthError), "Given array length does not meet the requirement.",
.value = 1, STATUS_ERROR, &ErrorStatus);
.description = "Given array length does not meet the requirement.",
.characteristic = STATUS_ERROR,
.loc = __GLOBAL__,
.prev = (Status *)&ErrorStatus
};
static const Status VariableFormatMismatch = (Status){ DEFSTATUS(VariableFormatMismatch, 1,
.identity = nameof(VariableFormatMismatch), "Given format does not match with given subjects.",
.value = 1, STATUS_ERROR, &ErrorStatus);
.description = "Given format does not match with given subjects.",
.characteristic = STATUS_ERROR, DEFSTATUS(ImprecisionError, 1,
.loc = __GLOBAL__, "Precision was not enough for handling the calculation.",
.prev = (Status *)&ErrorStatus STATUS_ERROR, &RuntimeError);
};
static const Status ImprecisionError = (Status){
.identity = nameof(ImprecisionError),
.value = 1,
.description = "Precision was not enough for handling the calculation.",
.characteristic = STATUS_ERROR,
.loc = __GLOBAL__,
.prev = (Status *)&RuntimeError
};
// ---------------------USER DEFINED----------------------- // ---------------------USER DEFINED-----------------------
static const Status UnavailableInstance = (Status){ DEFSTATUS(UnavailableInstance, 1,
.identity = nameof(UnavailableInstance), "An unavailable instance was given for initialisation.",
.value = 1, STATUS_ERROR, &NullPointerAccounted);
.description = "An unavailable instance was given for initialisation.",
.characteristic = STATUS_ERROR,
.loc = __GLOBAL__,
.prev = (Status *)&NullPointerAccounted
};
static const Status RecreationOnInstanceStillAlive = (Status){ DEFSTATUS(RecreationOnInstanceStillAlive, 1,
.identity = nameof(RecreationOnInstanceStillAlive), "Given instance was still alive, yet, was sent for another session of recreation.",
.value = 1, STATUS_ERROR, &InstanceStillAlive);
.description = "Given instance was still alive, yet, was sent for another "
"session of recreation.",
.characteristic = STATUS_ERROR,
.loc = __GLOBAL__,
.prev = (Status *)&InstanceStillAlive\
};
static const Status UnavailableParameter = (Status){ DEFSTATUS(UnavailableParameter, 1,
.identity = nameof(UnavailableParameter), "An unavailable instance was given as a parameter.",
.value = 1, STATUS_ERROR, &UnavailableInstance);
.description = "An unavailable instance was given as a parameter.",
.characteristic = STATUS_ERROR,
.loc = __GLOBAL__,
.prev = (Status *)&UnavailableInstance
};
static const Status InvalidReportTask = (Status){ DEFSTATUS(InvalidReportTask, 1,
.identity = nameof(InvalidReportTask), "An unavailable or illegal report task was given.",
.value = 1, STATUS_ERROR, &InvalidParameter);
.description = "An unavailable or illegal report task was given.",
.characteristic = STATUS_ERROR,
.loc = __GLOBAL__,
.prev = (Status *)&InvalidParameter
};
static const Status UnableToThrowError = (Status){ DEFSTATUS(UnableToThrowError, 1,
.identity = nameof(UnableToThrowError), "Unable to report an exceptional situation.",
.value = 1, STATUS_ERROR, &RuntimeError);
.description = "Unable to report an exceptional situation.",
.characteristic = STATUS_ERROR,
.loc = __GLOBAL__,
.prev = (Status *)&RuntimeError
};
static const Status ReadWriteError = (Status){ DEFSTATUS(ReadWriteError, 1,
.identity = nameof(ReadWriteError), "Error occurred during IO session.",
.value = 1, STATUS_ERROR, &RuntimeError);
.description = "Error occurred during IO session.",
.characteristic = STATUS_ERROR,
.loc = __GLOBAL__,
.prev = (Status *)&RuntimeError
};
static const Status FileNotFound = (Status){ DEFSTATUS(FileNotFound, 1,
.identity = nameof(FileNotFound), "Target file was unavailable and unable to find.",
.value = 1, STATUS_ERROR, &ReadWriteError);
.description = "Target file was unavailable and unable to find.",
.characteristic = STATUS_ERROR,
.loc = __GLOBAL__,
.prev = (Status *)&ReadWriteError
};
static const Status InvalidFileName = (Status){ DEFSTATUS(InvalidFileName, 1,
.identity = nameof(InvalidFileName), "Given file name was invalid.",
.value = 1, STATUS_ERROR, &ReadWriteError);
.description = "Given file name was invalid.",
.characteristic = STATUS_ERROR,
.loc = __GLOBAL__,
.prev = (Status *)&ReadWriteError
};
static const Status UnavailableFileName = (Status){ DEFSTATUS(UnavailableFileName, 1,
.identity = nameof(UnavailableFileName), "Given file name was unavailable.",
.value = 1, STATUS_ERROR, &UnavailableObject);
.description = "Given file name was unavailable",
.characteristic = STATUS_ERROR,
.loc = __GLOBAL__,
.prev = (Status *)&UnavailableObject
};
static const Status ReportThrown = (Status){ DEFSTATUS(UnavailableFileAccessMode, 1,
.identity = nameof(ReportThrown), "Given file accessing mode was unavailable.",
.value = 1, STATUS_ERROR, &UnavailableObject);
.description = "This function has thrown a report, "
"following instructions aborted.",
.characteristic = STATUS_ERROR,
.loc = __GLOBAL__,
.prev = (Status *)&RuntimeError\
};
static const Status ReportMessageTooLong = (Status){ DEFSTATUS(InsufficientAccessPermission, 1,
.identity = nameof(ReportMessageTooLong), "Given permission does not suffice to access.",
.value = 1, STATUS_ERROR, &ReadWriteError);
.description = "Given message is too long.",
.characteristic = STATUS_ERROR,
.loc = __GLOBAL__,
.prev = (Status *)&ArrayLengthError
};
static const Status MaximumLengthExceeded = (Status){ DEFSTATUS(ReportThrown, 1,
.identity = nameof(MaximumLengthExceeded), "This function has thrown a report, following instructions aborted.",
.value = 1, STATUS_ERROR, &RuntimeError);
.description = "Buffer was too long.",
.characteristic = STATUS_ERROR,
.loc = __GLOBAL__,
.prev = (Status *)&ArrayLengthError
};
static const Status MaximumLiteralisationLengthExceeded = (Status){ DEFSTATUS(ReportMessageTooLong, 1,
.identity = nameof(MaximumLiteralisationLengthExceeded), "Given message is too long.",
.value = 1, STATUS_ERROR, &ArrayLengthError);
.description = "Literalisation was too long.",
.characteristic = STATUS_ERROR,
.loc = __GLOBAL__,
.prev = (Status *)&MaximumLengthExceeded
};
static const Status UnavailableBuffer = (Status){ DEFSTATUS(MaximumLengthExceeded, 1,
.identity = nameof(UnavailableBuffer), "Maximum length had exceeded",
.value = 1, STATUS_ERROR, &ArrayLengthError);
.description = "Given buffer was unavailable.",
.characteristic = STATUS_ERROR, DEFSTATUS(MaximumLiteralisationLengthExceeded, 1,
.loc = __GLOBAL__, "Literalisation was too long",
.prev = (Status *)&UnavailableInstance STATUS_ERROR, &MaximumLengthExceeded);
};
DEFSTATUS(UnavailableBuffer, 1,
"Given buffer was unavailable.",
STATUS_ERROR, &UnavailableInstance);
DEFSTATUS(InvalidLiteralisingBuffer, 1,
"Given buffer does not have a good integrity on its length.",
STATUS_ERROR, &InvalidObject);
static const Status InvalidLiteralisingBuffer = (Status){
.identity = nameof(InvalidLiteralisingBuffer),
.value = 1,
.description = "Given buffer does not have a good integrity on its length.",
.characteristic = STATUS_ERROR,
.loc = __GLOBAL__,
.prev = (Status *)&InvalidObject
};
// ======================================================== // ========================================================

View File

@@ -1,39 +1,33 @@
#include <Compound/common.h>
#include <Compound/status.h> #include <Compound/status.h>
#include <Compound/utils.h>
/*
typedef struct {
char *file;
int line;
char *func;
} Location;
*/
Status Location_Literalise(Location *inst, char *buff) Status Location_Literalise(Location *inst, char *buff)
{ {
fails(inst, UnavailableInstance); fails(inst, apply(UnavailableInstance));
fails(buff, UnavailableBuffer); fails(buff, apply(UnavailableBuffer));
/* Literalise line. */ /* Literalise line. */
char line_buff[LITERALISATION_LENGTH_MAXIMUM]; char line_buff[LITERALISATION_LENGTH_MAXIMUM];
Utils_LiteraliseInteger(inst->line, line_buff); Utils_LiteraliseInteger(inst->line, line_buff);
/* Concatenate every buff. */ /* Concatenate every buff. */
const long total_len = strlen(inst->file) + strlen(line_buff) const long total_len = strlen(strnil(inst->file)) + strlen(strnil(line_buff))
+ strlen(inst->func) + strlen(strnil(inst->func))
+ LOCATION_LITERALISE_FORMAT_LENGTH; + LOCATION_LITERALISE_FORMAT_LENGTH;
state(total_len > LITERALISATION_LENGTH_MAXIMUM, state(total_len > LITERALISATION_LENGTH_MAXIMUM,
MaximumLiteralisationLengthExceeded); apply(MaximumLiteralisationLengthExceeded));
/* Copy and assign. */ /* Copy and assign. */
return (Status) { // return value(UnknownStatus,
.value = !sprintf(buff, LOCATION_LITERALISE_FORMAT, // !sprintf(buff, LOCATION_LITERALISE_FORMAT,
inst->file, inst->line, inst->func), // inst->file, inst->line, inst->func));
.description = NormalStatus.description, const int written =
.characteristic = NormalStatus.characteristic, sprintf(buff, LOCATION_LITERALISE_FORMAT,inst->file,inst->line,inst->func);
.loc = __HERE__,
.prev = NormalStatus.prev // written in "value" is absolutely ZERO.
}; state(!written, apply(value(UnknownStatus, written)));
return apply(NormalStatus);
} }
bool Location_Equal(Location *lc1, Location *lc2) bool Location_Equal(Location *lc1, Location *lc2)
@@ -62,24 +56,36 @@ bool Status_Equal(Status *stat1, Status *stat2)
Status Status_Literalise(Status *inst, char *buff) Status Status_Literalise(Status *inst, char *buff)
{ {
/* Skip unavailable instance and invalid parameter. */ /* Skip unavailable instance and invalid parameter. */
fails(inst, UnavailableInstance); fails(inst, apply(UnavailableInstance));
fails(buff, UnavailableBuffer); fails(buff, apply(UnavailableBuffer));
/* Literalise loc. */ /* Literalise loc. */
char loc_buff[LITERALISATION_LENGTH_MAXIMUM]; char loc_buff[LITERALISATION_LENGTH_MAXIMUM];
notok(Location_Literalise(&inst->loc, loc_buff), { notok(Location_Literalise(&inst->loc, loc_buff), {
return error(_, "Failed on literalising the \"loc\" of a status."); return _;
}); });
/* Styling output. */
const char *fmt;
if (inst->characteristic == STATUS_ERROR) {
// TODO(william): Replace following line with coloured-term-output function.
fmt = "\e[38;5;9m\e[4m\e[1m"STATUS_LITERALISE_FORMAT"\e[0m";
} else if (inst->characteristic == STATUS_UNKNOWN) {
// TODO(william): Replace following line with coloured-term-output function.
fmt = "\e[38;5;11m\e[4m"STATUS_LITERALISE_FORMAT"\e[0m";
} else {
// TODO(william): Replace following line with coloured-term-output function.
fmt = "\e[38;5;10m\e[2m"STATUS_LITERALISE_FORMAT"\e[0m";
}
/* Concatenate every buffer. */ /* Concatenate every buffer. */
state(!sprintf(buff, STATUS_LITERALISE_FORMAT, state(!sprintf(buff, fmt,
inst->identity, inst->description, inst->identity, inst->description,
(!inst->prev ? "(null)" : (inst->prev->identity)), (!inst->prev ? "(null)" : (inst->prev->identity)),
inst->value, inst->characteristic, loc_buff), inst->value, inst->characteristic, loc_buff),
error(RuntimeError, "Returned 0 byte written on concatenating buffers " apply(error(ReadWriteError, "No bytes were written into buffer.")));
"during literalisation of a status using \"sprintf\"."));
return NormalStatus; return apply(NormalStatus);
} }
bool StatusUtils_HasPrev(Status stat) bool StatusUtils_HasPrev(Status stat)
@@ -107,7 +113,7 @@ void StatusUtils_Dump(Status *inst, Status *store, int idx)
{ {
/* Skip when either stat or stat.prev is unavailable, or, idx is invalid. */ /* Skip when either stat or stat.prev is unavailable, or, idx is invalid. */
solve((!store || !StatusUtils_HasPrev(*inst) || idx < 0), return;); svoid((!store || !StatusUtils_HasPrev(*inst) || idx < 0));
store[idx] = *inst; store[idx] = *inst;
@@ -131,10 +137,10 @@ Status Report_Create(Report *inst, Status *stat, FILE *dest, char *initiator,
int priority) int priority)
{ {
/* Skip unavailable parameters. */ /* Skip unavailable parameters. */
fails(inst, UnavailableInstance); fails(inst, apply(UnavailableInstance));
fails(stat, error(InvalidParameter, "Given stat was null.")); fails(stat, apply(error(InvalidParameter, "Given stat was null.")));
fails(initiator, error(InvalidParameter, "Given initiator was null.")); fails(initiator, apply(error(InvalidParameter, "Given initiator was null.")));
state(priority < 0, error(InvalidParameter, "Given priority was negative.")); state(priority < 0, apply(error(InvalidParameter, "Given priority was negative.")));
/* Copy and assign. */ /* Copy and assign. */
inst->status = *stat; inst->status = *stat;
@@ -142,25 +148,26 @@ Status Report_Create(Report *inst, Status *stat, FILE *dest, char *initiator,
(void)strcpy(inst->initiator, initiator); (void)strcpy(inst->initiator, initiator);
inst->time = time(NULL); inst->time = time(NULL);
inst->priority = priority; inst->priority = priority;
inst->task_status = REPORT_SENDING_TASK_STATUS_PENDING; inst->taskprint_status = REPORT_SENDING_TASK_STATUS_PENDING;
inst->dest = (dest == NULL ? stdout : dest); inst->dest = (dest == NULL ? stdout : dest);
return NormalStatus; return apply(NormalStatus);
} }
Status Report_CopyOf(Report *inst, Report *other) Status Report_CopyOf(Report *inst, Report *other)
{ {
fails(inst, UnavailableInstance); fails(inst, apply(UnavailableInstance));
fails(other, error(InvalidParameter, "Given report is unavailable.")); fails(other, apply(error(InvalidParameter, "Given report is unavailable.")));
// Status status; // Status status;
// char *initiator; // char *initiator;
// time_t time; // time_t time;
// ReportSendingPriority priority; // ReportSendingPriority priority;
// ReportSendingTaskStatus task_status; // ReportSendingTaskStatus taskprint_status;
// FILE *dest; // FILE *dest;
inst->status = other->status; inst->status = other->status;
return apply(NormalStatus);
} }
void Report_Delete(Report *inst) void Report_Delete(Report *inst)
@@ -172,15 +179,15 @@ void Report_Delete(Report *inst)
inst->dest = NULL; inst->dest = NULL;
inst->priority = 0; inst->priority = 0;
inst->status = (Status){}; inst->status = (Status){};
inst->task_status = REPORT_SENDING_TASK_STATUS_NOTFOUND; inst->taskprint_status = REPORT_SENDING_TASK_STATUS_NOTFOUND;
inst->time = 0; inst->time = 0;
inst = NULL; inst = NULL;
} }
Status Report_Literalise(Report *inst, char *buff) Status Report_Literalise(Report *inst, char *buff)
{ {
fails(inst, UnavailableInstance); fails(inst, apply(UnavailableInstance));
fails(buff, UnavailableBuffer); fails(buff, apply(UnavailableBuffer));
// state(strlen(buff) != LITERALISATION_LENGTH_MAXIMUM, // state(strlen(buff) != LITERALISATION_LENGTH_MAXIMUM,
// InvalidLiteralisingBuffer); // InvalidLiteralisingBuffer);
@@ -208,9 +215,9 @@ Status Report_Literalise(Report *inst, char *buff)
idx += Utils_LiteraliseInteger(inst->priority, priority_literalising); idx += Utils_LiteraliseInteger(inst->priority, priority_literalising);
/** fin **/ /** fin **/
/** Task_status literalisation. **/ /** Taskprint_status literalisation. **/
char task_status_literalising[LITERALISATION_LENGTH_MAXIMUM]; char taskprint_status_literalising[LITERALISATION_LENGTH_MAXIMUM];
idx += Utils_LiteraliseInteger(inst->task_status, task_status_literalising); idx += Utils_LiteraliseInteger(inst->taskprint_status, taskprint_status_literalising);
/** fin **/ /** fin **/
/** Dest literalisation. **/ /** Dest literalisation. **/
@@ -226,18 +233,18 @@ Status Report_Literalise(Report *inst, char *buff)
strcpy(report_literalising, status_literalising); strcpy(report_literalising, status_literalising);
strcpy(report_literalising, time_literalising); strcpy(report_literalising, time_literalising);
strcpy(report_literalising, priority_literalising); strcpy(report_literalising, priority_literalising);
strcpy(report_literalising, task_status_literalising); strcpy(report_literalising, taskprint_status_literalising);
strcpy(report_literalising, dest_literalising); strcpy(report_literalising, dest_literalising);
strcpy(buff, report_literalising); strcpy(buff, report_literalising);
/* fin */ /* fin */
return NormalStatus; return apply(NormalStatus);
} }
Status ReportSender_Create(ReportSender *inst, Report *report) Status ReportSender_Create(ReportSender *inst, Report *report)
{ {
fails(inst, UnavailableInstance); fails(inst, apply(UnavailableInstance));
fails(report, error(UnavailableParameter, "Given report was unavailable.")); fails(report, error(UnavailableParameter, "Given report was unavailable."));
thrd_create(&inst->thread, &HANDLER, report); thrd_create(&inst->thread, &HANDLER, report);
@@ -248,7 +255,7 @@ Status ReportSender_Create(ReportSender *inst, Report *report)
inst->result = REPORT_SENDER_RESULT_PENDING; inst->result = REPORT_SENDER_RESULT_PENDING;
inst->successful = false; inst->successful = false;
return NormalStatus; return apply(NormalStatus);
} }
Status ReportSender_Send(ReportSender *inst, ReportSendingTask task) Status ReportSender_Send(ReportSender *inst, ReportSendingTask task)
@@ -264,12 +271,12 @@ Status ReportSender_Send(ReportSender *inst, ReportSendingTask task)
// // TODO(william): HERE, Report_Literalise // // TODO(william): HERE, Report_Literalise
// /* Write/Send data. */ // /* Write/Send data. */
// inst->report->task_status = REPORT_SENDING_TASK_STATUS_PROCEEDING; // inst->report->taskprint_status = REPORT_SENDING_TASK_STATUS_PROCEEDING;
// if (!fprintf(dest, buff)) { // if (!fprintf(dest, buff)) {
// } // }
// /* Sent successfully! Mark down properties. */ // /* Sent successfully! Mark down properties. */
return NormalStatus; return apply(NormalStatus);
} }
// bool arguestarter_equal(ArgueStarter *inst1, ArgueStarter *inst2) // bool arguestarter_equal(ArgueStarter *inst1, ArgueStarter *inst2)

View File

@@ -73,7 +73,7 @@ Status StringUtils_ToUnsignedComplexLongLongInteger(String *inst, unsigned _Comp
Status StringUtils_ToAddress(String *inst, void **store); Status StringUtils_ToAddress(String *inst, void **store);
Status StringUtils_ToCharBuff(String *inst, char const *buff, int base); Status StringUtils_ToCharBuff(String *inst, char const *buff, int base);
Status StringUtils_ToWideCharBuff(String *inst, wchar_t const *wbuff, int base); Status StringUtils_ToWideCharBuff(String *inst, wchar_t const *wbuff, int base);
Status StringUtils_Format(String *inst, const String *__restrict fmt, ...); Status StringUtils_Format(String *inst, const String *restrict fmt, ...);
Status StringUtils_Tokenise(String *inst, const String *delim, String *store); Status StringUtils_Tokenise(String *inst, const String *delim, String *store);
Status String_Encode(String *inst, StringEncoding encoding) Status String_Encode(String *inst, StringEncoding encoding)
throws(UnsupportedEncoding EncodingError DecodingError); throws(UnsupportedEncoding EncodingError DecodingError);

View File

@@ -5,32 +5,42 @@ Status String_Create(String *inst, int len)
/* Create an array has length len + 1, for termination character in string. */ /* Create an array has length len + 1, for termination character in string. */
ensure(Array_Create(inst, len + 1, sizeof(int)), "Failed to create a string."); ensure(Array_Create(inst, len + 1, sizeof(int)), "Failed to create a string.");
return NormalStatus; return apply(NormalStatus);
} }
Status String_CopyOf(String *inst, String *other) Status String_CopyOf(String *inst, String *other)
{ {
fails(inst, UnavailableInstance); fails(inst, apply(UnavailableInstance));
return apply(NormalStatus);
} }
Status String_Delete(String *inst) Status String_Delete(String *inst)
{ {
fails(inst, UnavailableInstance); fails(inst, apply(UnavailableInstance));
return apply(NormalStatus);
} }
Status String_GetAt(String *inst, Char *store, int index) Status String_GetAt(String *inst, Char *store, int index)
{ {
fails(inst, UnavailableInstance); fails(inst, apply(UnavailableInstance));
return apply(NormalStatus);
} }
Status String_SetAt(String *inst, Char *source, int index) Status String_SetAt(String *inst, Char *source, int index)
{ {
fails(inst, UnavailableInstance); fails(inst, apply(UnavailableInstance));
return apply(NormalStatus);
} }
Status String_Literalise(String *inst, String *store) Status String_Literalise(String *inst, String *store)
{ {
fails(inst, UnavailableInstance); fails(inst, apply(UnavailableInstance));
return apply(NormalStatus);
} }
int StringUtils_Compare(String *a, String *b) int StringUtils_Compare(String *a, String *b)

View File

@@ -2,22 +2,22 @@
Status Var_Create(Var *inst, size_t size) Status Var_Create(Var *inst, size_t size)
{ {
fails(inst, UnavailableInstance); fails(inst, apply(UnavailableInstance));
state(inst->alive, InstanceStillAlive); state(inst->alive, apply(InstanceStillAlive));
state(!size, normal(NormalStatus, "Exited with given parameter" state(!size,
"size as ZERO.")); apply(normal(NormalStatus, "Exited with given parameter size as ZERO.")));
state(((inst->addr = malloc(size)) == NULL), InsufficientMemory); state(((inst->addr = malloc(size)) == NULL), apply(InsufficientMemory));
inst->size = size; inst->size = size;
inst->alive = true; inst->alive = true;
return NormalStatus; return apply(NormalStatus);
} }
// Status Var_Create(Var *inst, void *addr, size_t size, char *identity) // Status Var_Create(Var *inst, void *addr, size_t size, char *identity)
// { // {
// /* Skip when inst is unavailable. */ // /* Skip when inst is unavailable. */
// fails(inst, UnavailableInstance); // fails(inst, apply(UnavailableInstance));
// /* Skip when identity is unavailable. */ // /* Skip when identity is unavailable. */
// fails(identity, NullPointerAccounted); // fails(identity, NullPointerAccounted);
// /* Skip when identity does not pass the examine. */ // /* Skip when identity does not pass the examine. */
@@ -27,22 +27,22 @@ Status Var_Create(Var *inst, size_t size)
// inst->size = size; // inst->size = size;
// *inst->identity = *identity; // *inst->identity = *identity;
// return NormalStatus; // return apply(NormalStatus);
// } // }
Status Var_CopyOf(Var *inst, Var *other) Status Var_CopyOf(Var *inst, Var *other)
{ {
/* Skip when inst or other is unavailable. */ /* Skip when inst or other is unavailable. */
fails(inst, UnavailableInstance); fails(inst, apply(UnavailableInstance));
state(inst->alive, InstanceStillAlive); state(inst->alive, apply(InstanceStillAlive));
fails(other, InvalidParameter); fails(other, apply(InvalidParameter));
/* Copy members from other. Only has to apply size, no addr is needed. */ /* Copy members from other. Only has to apply size, no addr is needed. */
state(!((inst->addr = malloc(other->size))), InsufficientMemory); state(!((inst->addr = malloc(other->size))), apply(InsufficientMemory));
inst->size = other->size; inst->size = other->size;
inst->alive = true; inst->alive = true;
return NormalStatus; return apply(NormalStatus);
} }
void Var_Delete(Var *inst) void Var_Delete(Var *inst)
@@ -77,13 +77,14 @@ void VarUtils_Swap(Var *v1, Var *v2)
Status Var_Literalise(Var *inst, char *buff) Status Var_Literalise(Var *inst, char *buff)
{ {
/* Skip when inst is unavailable. */ /* Skip when inst is unavailable. */
state(!inst, UnavailableInstance); state(!inst, apply(UnavailableInstance));
/* Write into buffer. */ /* Write into buffer. */
state(!sprintf(buff, VAR_LITERALISE_FORMAT"\n", inst->addr, inst->size), state(!sprintf(buff, VAR_LITERALISE_FORMAT"\n", inst->addr, inst->size),
error(RuntimeError, "Sprintf returned 0 where it should never do.")); apply(
error(RuntimeError, "Sprintf returned 0 where it should never do.")));
return NormalStatus; return apply(NormalStatus);
} }
bool Var_Equals(Var *a, Var *b) bool Var_Equals(Var *a, Var *b)

79
catlog.c Executable file → Normal file
View File

@@ -1,30 +1,32 @@
#include <Compound/catlog.h> #include "Status/include/status.h"
#include <Compound/common.h>
#include <Compound/status.h> #include <Compound/status.h>
#include <Compound/catlog.h>
Status CatlogMsg_Create(CatlogMsg *inst, CatlogLevel level, Status CatlogMsg_Create(CatlogMsg *inst, CatlogLevel level,
char *initiator, char *msg) char *initiator, char *msg)
{ {
/* Skip unavailable instances and parameters. */ /* Skip unavailable instances and parameters. */
fails(inst, UnavailableInstance); fails(inst, apply(UnavailableInstance));
state((initiator == NULL || msg == NULL), InvalidParameter); state((initiator == NULL || msg == NULL), apply(InvalidParameter));
inst->time = time(NULL); inst->time = time(NULL);
inst->level = level; inst->level = level;
inst->initiator = initiator; inst->initiator = initiator;
inst->content = msg; inst->content = msg;
return NormalStatus; return apply(NormalStatus);
} }
Status CatlogMsg_CopyOf(CatlogMsg *inst, CatlogMsg *other) Status CatlogMsg_CopyOf(CatlogMsg *inst, CatlogMsg *other)
{ {
/* Skip unavailable instances and parameters. */ /* Skip unavailable instances and parameters. */
fails(inst, UnavailableInstance); fails(inst, apply(UnavailableInstance));
fails(other, InvalidParameter); fails(other, apply(InvalidParameter));
*inst = *other; *inst = *other;
return NormalStatus; return apply(NormalStatus);
} }
bool CatlogMsg_Equals(CatlogMsg *inst, CatlogMsg *other) bool CatlogMsg_Equals(CatlogMsg *inst, CatlogMsg *other)
@@ -43,23 +45,23 @@ bool CatlogMsg_Equals(CatlogMsg *inst, CatlogMsg *other)
Status CatlogSender_Create(CatlogSender *inst, CatlogMsg *msg, FILE *dst) Status CatlogSender_Create(CatlogSender *inst, CatlogMsg *msg, FILE *dst)
{ {
/* Skip unavailable instances and parameters. */ /* Skip unavailable instances and parameters. */
fails(inst, UnavailableInstance); fails(inst, apply(UnavailableInstance));
fails(msg, InvalidParameter); fails(msg, apply(InvalidParameter));
/* Copy and assign, with detections. */ /* Copy and assign. */
inst->msg = *msg; inst->msg = *msg;
inst->dst = (dst == NULL ? (stdout) : dst); inst->dst = (!dst ? stdout : dst);
inst->successful = false; inst->successful = false;
inst->elapsed = (struct timespec){.tv_sec = 0, .tv_nsec = 0}; inst->elapsed = (struct timespec){ .tv_sec = 0, .tv_nsec = 0 };
return NormalStatus; return apply(NormalStatus);
} }
Status CatlogSender_CopyOf(CatlogSender *inst, CatlogSender *other) Status CatlogSender_CopyOf(CatlogSender *inst, CatlogSender *other)
{ {
/* Skip unavailable instances and parameters. */ /* Skip unavailable instances and parameters. */
fails(inst, UnavailableInstance); fails(inst, apply(UnavailableInstance));
fails(other, InvalidParameter); fails(other, apply(InvalidParameter));
/* Copy and assign */ /* Copy and assign */
inst->msg = other->msg; inst->msg = other->msg;
@@ -67,7 +69,7 @@ Status CatlogSender_CopyOf(CatlogSender *inst, CatlogSender *other)
inst->successful = other->successful; inst->successful = other->successful;
inst->elapsed = other->elapsed; inst->elapsed = other->elapsed;
return NormalStatus; return apply(NormalStatus);
} }
bool CatlogSender_Equals(CatlogSender *inst, CatlogSender *other) bool CatlogSender_Equals(CatlogSender *inst, CatlogSender *other)
@@ -84,35 +86,38 @@ bool CatlogSender_Equals(CatlogSender *inst, CatlogSender *other)
); );
} }
Status CatlogSender_Send(CatlogSender *inst, char *filepath, bool append) Status CatlogSender_Send(CatlogSender *inst)
throws(ReadWriteError)
{ {
/* Skip unavailable instances and parameters. */ /* Skip unavailable instances and parameters. */
fails(inst, UnavailableInstance); fails(inst, apply(UnavailableInstance));
fails(filepath, UnavailableFileName);
/* Open file. */ const int written = fprintf(inst->dst, "%s", inst->msg.content);
// ensure(CatlogUtils_OpenFile(inst->dst, (append ? "a" : "w")),
// "Unable to open file.");
(void)CatlogUtils_OpenFile(inst->dst, filepath, (append ? "a" : "w"));
/* Write msg. */ /* Write msg. */
return unknown(NormalStatus, "", !fprintf(inst->dst, "%s", inst->msg.content)); state(!written, error(ReadWriteError, "No bytes were written into buffer."));
return apply(NormalStatus);
} }
Status CatlogUtils_CalcElapsed(struct timespec t1, struct timespec t2); Status CatlogUtils_OpenFile(FILE **fileptr, const char *filepath,
const char const *restrict mode)
Status CatlogUtils_OpenFile(FILE *store, char *filepath,
const char const *__restrict mode)
{ {
/* No need to open a system output stream. */ /* Skip unavailable instances and parameters. */
if (!strcmp(filepath, "stdin") || fails(fileptr, apply(UnavailableBuffer));
!strcmp(filepath, "stdout") || fails(filepath, apply(UnavailableFileName));
!strcmp(filepath, "stderr")) { fails(mode, apply(UnavailableFileAccessMode));
return NormalStatus;
}
store = fopen(filepath, mode); /* Open the file. Return CatCannotOpenFile once failed. */
state(!(*fileptr = fopen(filepath, mode)), apply(CatCannotOpenFile));
return NormalStatus; return apply(NormalStatus);
}
Status CatlogUtils_CloseFile(FILE **fileptr)
{
/* Skip if either the fileptr or the *fileptr is unavailable. */
state(!fileptr || !*fileptr, apply(UnavailableParameter));
/* Return returning code of fclose, sealed with "value". */
return apply(value(UnknownStatus, fclose(*fileptr)));
} }

29
catlog.h Executable file → Normal file
View File

@@ -15,6 +15,26 @@ typedef enum {
CATLOG_LEVEL_NONE CATLOG_LEVEL_NONE
} CatlogLevel; } CatlogLevel;
DEFSTATUS(CatCannotSendMessage, 1,
"Cat had trouble while sending your message.",
STATUS_ERROR, &ReadWriteError);
DEFSTATUS(CatMessageTooLong, 1,
"Cat cannot finish reading your loooong message before deadline.",
STATUS_ERROR, &MaximumLengthExceeded);
DEFSTATUS(CatCannotFindFile, 1,
"Cat cannot have your file found.",
STATUS_ERROR, &FileNotFound);
DEFSTATUS(CatHasInsufficientPermission, 1,
"Cat cannot access your file with its given permission.",
STATUS_ERROR, &InsufficientAccessPermission);
DEFSTATUS(CatCannotOpenFile, 1,
"Cat cannot open your file because fopen returned NULL.",
STATUS_ERROR, &ReadWriteError);
typedef struct { typedef struct {
time_t time; time_t time;
CatlogLevel level; CatlogLevel level;
@@ -36,11 +56,10 @@ typedef struct {
Status CatlogSender_Create(CatlogSender *inst, CatlogMsg *msg, FILE *dst); Status CatlogSender_Create(CatlogSender *inst, CatlogMsg *msg, FILE *dst);
Status CatlogSender_CopyOf(CatlogSender *inst, CatlogSender *other); Status CatlogSender_CopyOf(CatlogSender *inst, CatlogSender *other);
Status CatlogSender_Send(CatlogSender *inst);
bool CatlogSender_Equals(CatlogSender *inst, CatlogSender *other); bool CatlogSender_Equals(CatlogSender *inst, CatlogSender *other);
Status CatlogSender_Send(CatlogSender *inst, char *filepath, bool append) Status CatlogUtils_OpenFile(FILE **fileptr, const char *filepath,
throws(ReadWriteError); const char const *restrict mode);
Status CatlogUtils_CalcElapsed(struct timespec t1, struct timespec t2); Status CatlogUtils_CloseFile(FILE **fileptr);
Status CatlogUtils_OpenFile(FILE *store, char *filepath,
const char const *__restrict mode);
#endif /* COMPOUND_CATLOG_H */ #endif /* COMPOUND_CATLOG_H */

150
common.h
View File

@@ -5,45 +5,27 @@
# include <stdlib.h> # include <stdlib.h>
# include <stdbool.h> # include <stdbool.h>
/** /* Get the literal. */
* @brief Return $n as the return value, once $o is NULL # define nameof(obj) #obj
* @return given $n as the return value
* @note "fails" stands for "Fails on Null Check"
* @note 'o' stands for "Object"
* @note 'n' stands for "Numeric on Return"
*/
# define fails(o, n) { if ((o) == NULL) return (n); }
/** /* Return $n as the return value, once $o is NULL. */
* @brief Return $e as the return value, once $v equals $e # define fails(o, n) { if (!o) return (n); }
* @return given $e as the return value
* @note "trans" stands for "Transits Error Code to Caller" /* Return $e as the return value, once $v equals $e. */
* @note 'v' stands for "Value"
* @note 'e' stands for "Error Code"
*/
# define trans(v, e) { if ((v) == (e)) return (e); } # define trans(v, e) { if ((v) == (e)) return (e); }
/** /* Evaluate given statement while the ptr to $s is not NULL. */
* @brief Evaluate given statement while the ptr to $s is not NULL
* @return given $n as the return value
* @note "state" stands for "Statement Evaluation"
* @note 's' stands for "Statement"
* @note 'n' stands for "Numeric on Return"
*/
# define state(s, n) { if ((s)) return (n); } # define state(s, n) { if ((s)) return (n); }
/** /* Evaluate given statement while the ptr to $s is not NULL. */
* @brief Evaluate given statement while the ptr to $s is not NULL
* @return nothing.
* @note "svoid" stands for "Statement Evaluation in Void"
* @note 's' stands for "Statement"
*/
# define svoid(s) { if ((s)) return; } # define svoid(s) { if ((s)) return; }
/* Another way to handle if statements more cleanly. */
# define solve(s, b) { if (s) b }
/* Create a new UnknownStatus on the fly. */ /* Create a new UnknownStatus on the fly. */
# define unknown(e, c, v) ((Status) {\ # define unknown(e, c, v) ((Status) {\
.identity = nameof(UnknownStatus),\ .identity = e.identity,\
.value = v,\ .value = v,\
.description = c,\ .description = c,\
.characteristic = STATUS_UNKNOWN,\ .characteristic = STATUS_UNKNOWN,\
@@ -53,7 +35,7 @@
/* Create a new NormalStatus on the fly. */ /* Create a new NormalStatus on the fly. */
# define normal(e, c) ((Status) {\ # define normal(e, c) ((Status) {\
.identity = nameof(NormalStatus),\ .identity = e.identity,\
.value = 0,\ .value = 0,\
.description = c,\ .description = c,\
.characteristic = STATUS_NORMAL,\ .characteristic = STATUS_NORMAL,\
@@ -63,7 +45,7 @@
/* Create a new ErrorStatus on the fly. */ /* Create a new ErrorStatus on the fly. */
# define error(e, c) ((Status) {\ # define error(e, c) ((Status) {\
.identity = nameof(ErrorStatus),\ .identity = e.identity,\
.value = e.value,\ .value = e.value,\
.description = c,\ .description = c,\
.characteristic = STATUS_ERROR,\ .characteristic = STATUS_ERROR,\
@@ -71,38 +53,56 @@
.prev = e.prev\ .prev = e.prev\
}) })
/* Extend the Status chain by giving 'p' for "predecessor" /* Extend the Status chain by giving 'p' for "predecessor" and 'e' for "Eval-Status". */
and 'e' for "Eval-Status". */
# define extend(p, e) ((Status) {\ # define extend(p, e) ((Status) {\
.identity = e.identity,\ .identity = e.identity,\
.value = p.value,\ .value = p.value,\
.description = e.description,\ .description = e.description,\
.characteristic = p.characteristic,\ .characteristic = p.characteristic,\
.loc = e.loc,\ .loc = __HERE__,\
.prev = &p\ .prev = &p\
}) })
/** @brief Create a report in place. # define value(e, v) ((Status) {\
* @return A instance of Status Report customised. .identity = e.identity,\
* @note "stamp" stands for "Report Stamp" .value = v,\
* @note 'e' stands for "Exception" .description = e.description,\
* @note 'c' stands for "Char String of Originator" .characteristic = e.characteristic,\
*/ .loc = __HERE__,\
.prev = (Status *)e.prev\
})
# define apply(e) ((Status) {\
.identity = e.identity,\
.value = e.value,\
.description = e.description,\
.characteristic = e.characteristic,\
.loc = __HERE__,\
.prev = (Status *)e.prev\
})
/* Create a report in place with $e for base and $c for initiator literal. */
# define stamp(e, c) ((Report) {\ # define stamp(e, c) ((Report) {\
.status = e,\ .status = e,\
.initiator = c,\ .initiator = c,\
.time = time(NULL),\ .time = time(NULL),\
.priority = REPORT_SENDING_PRIORITY_NORMAL,\ .priority = REPORT_SENDING_PRIORITY_NORMAL,\
.task_status = REPORT_SENDING_TASK_STATUS_PENDING\ .taskprint_status = REPORT_SENDING_TASK_STATUS_PENDING\
}) })
/** # define cat(s) {\
* @brief Another way to handle if statements more cleanly. CatlogMsg msg;\
* @note "solve" stands for "Solve with Statements." CatlogMsg_Create(&msg, CATLOG_LEVEL_DEBUG, "CAT", s);\
* @note 's' stands for "Statement" CatlogSender sender;\
* @note 'b' stands for "Block of Forks" CatlogSender_Create(&sender, &msg, stderr);\
*/ CatlogSender_Send(&sender);\
# define solve(s, b) if (s) b }
# define ok(s, b) { Status _ = s; if (StatusUtils_IsOkay(_)) b }
# define notok(s, b) { Status _ = s; if (!StatusUtils_IsOkay(_)) b }
# define seek(s, b) { Status _ = s; b }
// /** // /**
// * @brief Forcibly return desired value $v once $s is not $k. // * @brief Forcibly return desired value $v once $s is not $k.
@@ -116,8 +116,33 @@
// # define sforce(s, k, v) solve((!Status_Equal(s, k)), v) // # define sforce(s, k, v) solve((!Status_Equal(s, k)), v)
/* Get the literal. */ // # define print_status(s) {\
# define nameof(obj) #obj // Status _ = s;\
// char buff[LITERALISATION_LENGTH_MAXIMUM];\
// notok(Status_Literalise(&_, buff), {\
// (void)printf("Failed to literalise a status\n");\
// });\
// (void)printf("%s\n", buff);\
// }
# define print_status(s) {\
char buff[LITERALISATION_LENGTH_MAXIMUM];\
(void)Status_Literalise(&s, buff);\
(void)fprintf(stderr, "%s\n", buff);\
}
# define print_statusdump(s) {\
Status _ = s;\
const int dump_len = StatusUtils_Depth(&_);\
Status dump[dump_len];\
StatusUtils_Dump(&_, dump, 0);\
for (register int i = 0; i < dump_len; i++) {\
(void)printf("%d/%d\n", i, dump_len - 1);\
print_status(dump[i]);\
}\
}
# define strnil(s) (!s ? ("(null)") : s)
# define type(T) # define type(T)
@@ -126,31 +151,6 @@
# define String(T) String # define String(T) String
# define cat(s) {\
CatlogMsg msg;\
CatlogMsg_Create(&msg, CATLOG_LEVEL_DEBUG, "CAT", s);\
CatlogSender sender;\
CatlogSender_Create(&sender, &msg, stderr);\
CatlogSender_Send(&sender, "stdout", false);\
}
# define _status(s) {\
const Status _ = s;\
char buff[LITERALISATION_LENGTH_MAXIMUM];\
(void)Status_Literalise((Status *)&_, buff);\
(void)printf("%s\n", buff);\
}
# define ok(s, b) {\
const Status _ = s;\
if (StatusUtils_IsOkay(_)) b\
}
# define notok(s, b) {\
const Status _ = s;\
if (!StatusUtils_IsOkay(_)) b\
}
typedef enum { typedef enum {
COMMON_ERROR_NULLPTR = 1, COMMON_ERROR_NULLPTR = 1,
COMMON_ERROR_INVALID_ARGUMENT, COMMON_ERROR_INVALID_ARGUMENT,

View File

@@ -2,38 +2,38 @@
Status NameScope_Create(NameScope *inst) Status NameScope_Create(NameScope *inst)
{ {
fails(inst, UnavailableInstance); fails(inst, apply(UnavailableInstance));
/* Create instances for members from inst. */ /* Create instances for members from inst. */
state(StatusUtils_IsOkay(NameScope_EmptyName(&inst->latest)), state(StatusUtils_IsOkay(NameScope_EmptyName(&inst->latest)),
error(RuntimeError, "Failed to initialise latest from NameScope")); apply(error(RuntimeError, "Failed to initialise latest from NameScope")));
state(StatusUtils_IsOkay(NameScope_EmptyName(&inst->idx)), state(StatusUtils_IsOkay(NameScope_EmptyName(&inst->idx)),
error(RuntimeError, "Failed to initialise idx from NameScope")); apply(error(RuntimeError, "Failed to initialise idx from NameScope")));
state(StatusUtils_IsOkay(NameScope_EmptyName(inst->occupied)), state(StatusUtils_IsOkay(NameScope_EmptyName(inst->occupied)),
error(RuntimeError, "Failed to initialise occupied from NameScope")); apply(error(RuntimeError, "Failed to initialise occupied from NameScope")));
return NormalStatus; return apply(NormalStatus);
} }
Status NameScope_CopyOf(NameScope *inst, NameScope *other) Status NameScope_CopyOf(NameScope *inst, NameScope *other)
{ {
fails(inst, UnavailableInstance); fails(inst, apply(UnavailableInstance));
fails(other, UnavailableParameter); fails(other, apply(UnavailableParameter));
/* Copy and assign. */ /* Copy and assign. */
other->latest = inst->latest; other->latest = inst->latest;
other->idx = inst->idx; other->idx = inst->idx;
const Name len = ` const Name len = {};
`
NameScopeUtils_CalcNameArrayLength(&other->occupied); NameScopeUtils_CalcNameArrayLength(&other->occupied);
for (Name i = (Name){0}; (NameScope_CompareName(i, len) < 0);) { for (Name i = (Name){0}; (NameScope_CompareName(i, len) < 0);) {
// TODO(william): HERE // TODO(william): HERE
/* i++ */ /* i++ */
state((!StatusUtils_IsOkay(NameScope_CountUp(&i))), state((!StatusUtils_IsOkay(NameScope_CountUp(&i))),
error(RuntimeError, "Error occurred during calculations of Name.")); apply(error(RuntimeError, "Error occurred during calculations of Name.")));
} }
} }
@@ -49,9 +49,7 @@ Status NameScope_FormatTrim(Name *inst);
Status NameScope_FormatInflate(Name *inst); Status NameScope_FormatInflate(Name *inst);
Name ` // Status NameScopeUtils_CalcNameArrayLength(Name **arr);
`
NameScopeUtils_CalcNameArrayLength(Name **arr);
bool NameScope_IsAvailable(NameScope *inst, Name idx); bool NameScope_IsAvailable(NameScope *inst, Name idx);

View File

@@ -11,4 +11,7 @@
# error Platform not supported. Please issue this on github.com/Wilhelm-Lee/Compound --William # error Platform not supported. Please issue this on github.com/Wilhelm-Lee/Compound --William
# endif # endif
// # if defined _WIN16 || defined _WIN32 || defined _WIN64
// # define COMPOUND_STDIN_PATH
#endif /* COMPOUND_PLATFORM_H */ #endif /* COMPOUND_PLATFORM_H */