Phasor 2.2.0
Stack VM based Programming Language
Loading...
Searching...
No Matches
Repl.cpp
Go to the documentation of this file.
1#include "Repl.hpp"
2#include <filesystem>
3#include <fstream>
4#include <iostream>
5#include <memory>
6#include <sstream>
16
17namespace Phasor
18{
19
20Repl::Repl(int argc, char *argv[], char *envp[])
21{
22 m_args.envp = envp;
23}
24
26{
27 return runRepl();
28}
29
31{
32 auto vm = createVm();
33 Frontend::runRepl(vm.get());
34 return 0;
35}
36
37void Repl::runSourceString(const std::string &source, VM &vm)
38{
39 Lexer lexer(source);
40 auto tokens = lexer.tokenize();
41 Parser parser(tokens);
42 auto program = parser.parse();
43
44 CodeGenerator codegen;
45 auto bytecode = codegen.generate(*program);
46
47 vm.run(bytecode);
48}
49
50std::unique_ptr<VM> Repl::createVm()
51{
52 auto vm = std::make_unique<VM>();
54 StdLib::argv = m_args.scriptArgv;
55 StdLib::argc = m_args.scriptArgc;
56 StdLib::envp = m_args.envp;
57
58 vm->setImportHandler([vm_ptr = vm.get()](const std::filesystem::path &path) {
59 std::ifstream file(path);
60 if (!file.is_open())
61 throw std::runtime_error("Could not open imported file: " + path.string());
62 std::stringstream buffer;
63 buffer << file.rdbuf();
64 runSourceString(buffer.str(), *vm_ptr);
65 });
66
67 return vm;
68}
69
70} // namespace Phasor
Code generator for Phasor VM.
Definition CodeGen.hpp:243
Bytecode generate(const AST::Program &program, const std::map< std::string, int > &existingVars={}, int nextVarIdx=0, bool replMode=false)
Generate bytecode from program.
Definition CodeGen.cpp:7
Lexer.
Definition Lexer.hpp:30
std::vector< Token > tokenize()
Definition Lexer.cpp:25
Parser.
Definition Parser.hpp:12
std::unique_ptr< AST::Program > parse()
Definition Parser.cpp:13
int run()
Definition Repl.cpp:25
Repl(int argc, char *argv[], char *envp[])
Definition Repl.cpp:20
int runRepl()
Definition Repl.cpp:30
static void runSourceString(const std::string &source, VM &vm)
Definition Repl.cpp:37
std::unique_ptr< VM > createVm()
Definition Repl.cpp:50
AppArgs m_args
Definition Repl.hpp:38
static void registerFunctions(VM &vm)
Register all standard library functions.
Definition StdLib.cpp:10
static char ** argv
Command line arguments.
Definition StdLib.hpp:30
static int argc
Number of command line arguments.
Definition StdLib.hpp:31
static char ** envp
Environment variables.
Definition StdLib.hpp:32
Virtual Machine.
Definition VM.hpp:18
void run(const Bytecode &bytecode)
Run the virtual machine.
Definition VM.cpp:9
void runRepl(VM *vm=nullptr)
Run an REPL.
Definition Frontend.cpp:80
The Phasor Programming Language and Runtime.
Definition AST.hpp:8