Skip to content

Pipeline and API

WireWhiz edited this page May 10, 2023 · 3 revisions

As of now the bare minimum pipeline for loading a script and calling functions from it is as follows:

#include "script.h"
#include "scriptRuntime.h"
#include "staticAnalysis/constexprEvaluator.h"
#include "staticAnalysis/staticAnalyzer.h"

using namespace BraneScript;

int main()
{
    // Script to be compiled
    std::string testString = R"(
    export as "tests"
    {
        int add(int a, int b)
        {
           return a + b;
        }
    }
    )";

    /* The static analyzer is what checks the code for errors and reports them if found, 
     * it also creates the document context we generate the intermediate script from, it  
     * also provides helper functions to complete compilation 
     */
    StaticAnalyzer analyzer;
    // Loading a script extracts all the symbols (fuctions, structs, exported libs, etc) but does not error check or create DocumentContext
    analyzer.load("test", testString);

    //Validate then check to see if any errors were generated, if there were, print them and return with an error.
    // Validation is where the DocumentContext is generated
    if(!analyzer.validate("test"))
    {
        for(auto& error : analyzer.getCtx("test")->errors)
            std::cerr << "(" << error.range.start.line << ", " << error.range.start.charPos << ") " << error.message << std::endl;
        return 1
    }

    // Compile the script to a serializable intermediate representation, this is what you want to store/cache if you want to use a script later without compiling from source.
    auto ir = analyzer.compile("test");

    // Create a runtime and load our script, the runtime is what manages and stores the script and it's data. 
    ScriptRuntime rt;
    Script* testScript = rt.loadScript(ir);
    assert(testScript);

    // After loading our script we can now grab the function we want and call it.
    auto add = testScript->getFunction<int, int, int>("tests::add");
    if(!add)
    {
        std::cerr << "Could not find test function!" << std::endl;
        return 1;
    }
    std::cout << "Test function returned: " << add(2, 2) << std::endl;
    return 0;
}

Clone this wiki locally