aboutsummaryrefslogtreecommitdiffstats
path: root/forth.c
diff options
context:
space:
mode:
authordan <[email protected]>2023-06-03 14:41:14 -0400
committerdan <[email protected]>2023-06-03 14:41:14 -0400
commit48c02f4fccd13cf329594988a19a4edd1fce4774 (patch)
treea92d6af027aa5b9d3368801b770179cc83a928f3 /forth.c
parentf130b76fabb440b02c418a537074ec80489a9480 (diff)
downloadforth-48c02f4fccd13cf329594988a19a4edd1fce4774.tar.gz
forth-48c02f4fccd13cf329594988a19a4edd1fce4774.tar.bz2
forth-48c02f4fccd13cf329594988a19a4edd1fce4774.zip
feat: forthmachine and stack errors handled with error handlers, not just by printing
Diffstat (limited to 'forth.c')
-rw-r--r--forth.c47
1 files changed, 42 insertions, 5 deletions
diff --git a/forth.c b/forth.c
index e44d372..c70cc83 100644
--- a/forth.c
+++ b/forth.c
@@ -8,16 +8,42 @@
#include "stack.h"
#include "forthmachine.h"
+int exitcode = EXIT_SUCCESS;
+
+// Only used when in buffer_eval mode.
int initialised = false;
+// Only used when in buffer_eval mode.
forthmachine* fm;
-int lastline = 0;
+
+// Pointer to errormessage.
+// Only used when in buffer_eval mode.
+char* errormessage;
+
+void buffer_eval_handleerror(char* err) {
+ exitcode = EXIT_FAILURE;
+ // Set errormessage global
+ errormessage = malloc(sizeof(char) * MAX_OUTPUT_BUFFER_SIZE);
+ strcpy(errormessage, err);
+ #ifdef __EMSCRIPTEN__
+ initialised = false;
+ free(fm);
+ fm = NULL;
+ strcat(errormessage, "\nEnvironment has been reset.\n");
+ #endif
+}
+
+
char* buffer_eval(int len, char* line) {
if (!initialised) {
- fm = forthmachine_new();
+ // initialise global forthmachine instance on first call
+ fm = forthmachine_new(buffer_eval_handleerror);
initialised = true;
}
strcpy(fm->outputbuffer, "");
forthmachine_eval(fm, len, line);
+ if (exitcode == EXIT_FAILURE) {
+ return errormessage;
+ }
if (fm->outputbuffer && strlen(fm->outputbuffer)) {
return fm->outputbuffer;
} else {
@@ -25,8 +51,14 @@ char* buffer_eval(int len, char* line) {
}
}
+void error_print(char* error) {
+ exitcode = exitcode || EXIT_FAILURE;
+ fprintf(stderr, "%s\n", error);
+ exit(exitcode);
+}
+
void stdin_eval() {
- forthmachine* fm = forthmachine_new();
+ forthmachine* fm = forthmachine_new(error_print);
char *line = NULL;
size_t len = 0;
ssize_t read;
@@ -40,8 +72,12 @@ void stdin_eval() {
#ifndef __EMSCRIPTEN__
int main(int argc, char** argv) {
- if (argc>1) printf("%s", buffer_eval(strlen(argv[1])+1, argv[1]));
- else stdin_eval();
+ if (argc>1) {
+ printf("%s", buffer_eval(strlen(argv[1])+1, argv[1]));
+ } else {
+ stdin_eval();
+ }
+ return exitcode;
}
#else
@@ -50,6 +86,7 @@ int main(int argc, char** argv) {
#define EXTERN
EXTERN EMSCRIPTEN_KEEPALIVE char* extern_eval(char* line) {
+ exitcode = EXIT_SUCCESS;
return buffer_eval(strlen(line)+1, line);
}
#endif