I've created an interpreter for a stupid programming language in C++ and the whole core structure is finished (Tokenizer, Parser, Interpreter including Symbol tables, core functions, etc.).
Now I have a problem with creating and managing the function libraries for this interpreter (I'll explain what I mean with that later)
So currently my core function handler is horrible:
// Simplified version
myLangResult SystemFunction( name, argc, argv )
{
if ( name == "print" )
{
if( argc < 1 )
{
Error('blah');
}
cout << argv[ 0 ];
} else if ( name == "input" ) {
if( argc < 1 )
{
Error('blah');
}
string res;
getline( cin, res );
SetVariable( argv[ 0 ], res );
} else if ( name == "exit ) {
exit( 0 );
}
And now think of each else if being 10 times more complicated and there being 25 more system functions. Unmaintainable, feels horrible, is horrible.
So I thought: How to create some sort of libraries that contain all the functions and if they are imported initialize themselves and add their functions to the symbol table of the running interpreter.
However this is the point where I don't really know how to go on.
What I wanted to achieve is that there is e.g.: an (extern?) string library for my language, e.g.: string, and it is imported from within a program in that language, example:
import string
myString = "abcde"
print string.at( myString, 2 ) # output: c
My problems:
- How to separate the function libs from the core interpreter and load them?
- How to get all their functions into a list and add it to the symbol table when needed?
What I was thinking to do:
At the start of the interpreter, as all libraries are compiled with it, every single function calls something like RegisterFunction( string namespace, myLangResult (*functionPtr) );
which adds itself to a list. When import X
is then called from within the language, the list built with RegisterFunction is then added to the symbol table.
Disadvantages that spring to mind:
All libraries are directly in the interpreter core, size grows and it will definitely slow it down.