curly/interpreter.hpp

87 lines
2.0 KiB
C++

//
// interpreter.hpp
// curly
//
// Created by Bob Polis at 2020-09-05
// Copyright (c) 2020 SwiftCoder. All rights reserved.
//
#ifndef _interpreter_H_
#define _interpreter_H_
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <stdexcept>
#include <sstream>
class syntax_error : public std::runtime_error {
public:
syntax_error(const std::string& what_arg, size_t lineno)
: std::runtime_error {what_arg}, _lineno {lineno} {}
size_t lineno() const { return _lineno; }
private:
size_t _lineno {0};
};
class interpreter {
public:
interpreter() = default;
std::string eval(std::istream& in, bool& done);
private:
std::vector<std::string> _prog; // program lines without label defs or comments
std::vector<std::string> _values; // value stack
std::map<std::string, size_t> _labels; // label name => prog line index
std::map<std::string, std::string> _vars; // var name => string value
std::vector<size_t> _calls; // call stack
size_t _pc {0}; // current program counter (index into _prog)
std::vector<size_t> _pc_offsets; // removed line indices for prog index => source line
void reset();
void exec_instruction(const std::string& code, bool& done);
// integer operations
void add();
void sub();
void mul();
void div();
void mod();
void abs();
void neg();
void inc();
void dec();
// string operations
void dup();
void rev();
void slc();
void idx();
void cat();
void len();
void rot();
void enl();
// tests & jumps
void gto();
void geq();
void gne();
void glt();
void gle();
void ggt();
void gge();
// subroutines
void fun();
void ret();
// I/O
void inp();
void out();
void err();
};
#endif // _interpreter_H_