External library support

This commit is contained in:
2025-08-25 13:22:15 +10:00
parent 2f706e2285
commit 5bd8519517
3 changed files with 50 additions and 2 deletions

View File

@@ -41,6 +41,8 @@
#include <map> #include <map>
#include <stack> #include <stack>
#include <fstream> #include <fstream>
#include <cstdlib>
#include <filesystem>
using namespace std; using namespace std;
@@ -402,9 +404,15 @@ string procFnName = "";
bool inFunction = false; bool inFunction = false;
// Forward declaration for the call instruction // Forward declaration for the call instruction and use instruction
Literal exec(vector<Instruction> in); Literal exec(vector<Instruction> in);
// Forward declaration for the use instruction
vector<Instruction> parser(vector<vector<string>> in);
// Forward declaration for the use instruction
vector<vector<string>> lexer(string in);
/* /*
exec function exec function
This function takes a list of instructions (see Instruction struct above and parser This function takes a list of instructions (see Instruction struct above and parser
@@ -1734,7 +1742,39 @@ Literal exec(vector<Instruction> in, bool executingFunction) {
} }
break; break;
case Instructions::Use: case Instructions::Use:
cout << "Still to be implemented" << endl; if (l.args.size() < 1) {
error("Could not find all arguments for Use inbuilt");
}
{
string useName;
if (holds_alternative<Literal>(l.args[0])) {
if (holds_alternative<string>(get<Literal>(l.args[0]).val)) {
useName = get<string>(get<Literal>(l.args[0]).val) + ".grnd";
} else {
error("First argument for use requires a string literal");
}
} else {
error("First argument for use requires a string literal");
}
string groundLibsDir = getenv("GROUND_LIBS");
if (filesystem::exists(useName)) {
} else if (groundLibsDir != "" && filesystem::exists(groundLibsDir + useName)) {
useName = groundLibsDir + useName;
} else {
error("Could not find external Ground library in $GROUND_LIBS or current directory.");
}
ifstream file(useName);
string lns;
string in;
while (getline(file, lns)) {
in += lns += "\n";
}
Literal ret = exec(parser(lexer(in)), false); }
break; break;
case Instructions::Extern: case Instructions::Extern:
cout << "Still to be implemented" << endl; cout << "Still to be implemented" << endl;

3
tests/use/library.grnd Normal file
View File

@@ -0,0 +1,3 @@
fun -string !dingus
return "Hello from the library"
endfun

5
tests/use/use.grnd Normal file
View File

@@ -0,0 +1,5 @@
use "library"
call !dingus &var
stdlnout $var