From 28faf6142c1bf3d49b0d8065cee4748a87644c8e Mon Sep 17 00:00:00 2001 From: Maxwell Jeffress Date: Sun, 21 Sep 2025 08:55:50 +1000 Subject: [PATCH] basic version of catch --- src/main.cpp | 54 +++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 51 insertions(+), 3 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 189d829..9d77ed3 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -363,6 +363,12 @@ GroundValue literalToGroundValue(const Literal& lit) { return gv; } +/* + catches stackmap + This stores all catches in a scope, to catch errors before they happen. +*/ +stack> catches; + Literal groundValueToLiteral(const GroundValue& gv) { Literal lit; switch (gv.type) { @@ -385,14 +391,30 @@ Literal groundValueToLiteral(const GroundValue& gv) { return lit; } +// Forward declaration of setVal for error function +void setVal(string varName, Literal value); + /* error function Takes a string (which is a debug message) and prints it to the console, letting the user know what went wrong with the program. */ -void error(string in, string errCode = "syntaxError", int exitc = 1) { +int error(string in, string errCode = "syntaxError", int exitc = 1) { + int pops = 0; + while (catches.size() > 0) { + if (catches.top().find(errCode) != catches.top().end()) { + Literal tmpLit; + tmpLit.val = false; + setVal(catches.top()[errCode].varName, tmpLit); + return pops; + } else { + catches.pop(); + pops ++; + } + } cout << "\033[31m" + errCode + ": \033[39m" << in << endl; exit(exitc); + return pops; } /* @@ -590,6 +612,10 @@ void preProcessLabels(vector instructions) { function for the program. */ Literal exec(vector in, bool executingFunction) { + { + map tmp; + catches.push(tmp); + } for (int i = 0; i < in.size(); i++) { Instruction l = in[i]; if (processingFunction) { @@ -930,11 +956,33 @@ Literal exec(vector in, bool executingFunction) { if (l.args.size() < 2) { error("Could not find all arguments for Catch inbuilt"); } - if (holds_alternative(l.args[0])) { - if (holds_alternative(get(l.args[0]).val)) { + { + string errCode; + Direct varRef; + + if (holds_alternative(l.args[0])) { + if (holds_alternative(get(l.args[0]).val)) { + errCode = get(get(l.args[0]).val); + } else { + error("First argument of catch must be a string literal"); + } + } else { + error("First argument of catch must be a string literal"); } + + if (holds_alternative(l.args[1])) { + varRef = get(l.args[1]); + } else { + error("Second argument of catch must be a direct reference"); + } + + catches.top()[errCode] = varRef; + Literal tmpLit; + tmpLit.val = true; + setVal(varRef.varName, tmpLit); } + break; /* set instruction This instruction sets a variable to a provided value.