Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "ast.hpp"
- #include <regex>
- int32_t Interpret(
- InterpretContext &context, // Contains the parameters and variable bindings
- TreePtr program
- ){
- std::regex reNum("^-?[0-9]+$");
- std::regex reId("^[a-z][a-z 0-9]*$");
- if( regex_match(program->type, reNum) ){
- return std::atol(program->type.c_str());
- // TODO : Check for things matching reId
- }
- else if( regex_match(program->type, reId) ){
- return context.bindings[program->type.c_str()];
- }
- else if(program->type=="Param"){
- unsigned index=atol(program->value.c_str());
- auto value=context.params.at(index);
- return value;
- }
- else if(program->type=="Assign"){ //Works
- int32_t val = Interpret(context, program->branches.at(0));
- context.bindings[program->value.c_str()] = val;
- return val;
- }
- else if(program->type=="Input"){
- int32_t val;
- std::cin >> val;
- return val;
- }
- else if(program->type=="Output"){
- int32_t val=Interpret(context, program->branches.at(0));
- std::cout<<val<<std::endl;
- return val;
- // TODO: Handle other constructs
- }
- else if(program->type=="While"){
- while(Interpret(context, program->branches.at(0)) != 0){
- Interpret(context, program->branches.at(1));
- }
- return 0;
- }
- else if(program->type=="Seq"){ //Works
- int32_t val;
- int vecsize = program->branches.size();
- for(int i = 0; i < vecsize; i++){
- val = Interpret(context, program->branches.at(i));
- }
- return val;
- }
- else if(program->type=="Add"){
- int32_t leftval = Interpret(context, program->branches.at(0));
- int32_t rightval = Interpret(context, program->branches.at(1));
- int32_t val = leftval + rightval;
- return val;
- }
- else if(program->type=="Sub"){
- int32_t leftval = Interpret(context, program->branches.at(0));
- int32_t rightval = Interpret(context, program->branches.at(1));
- int32_t val = leftval - rightval;
- return val;
- }
- else if(program->type=="If"){
- int32_t val;
- if(Interpret(context, program->branches.at(0)) != 0){
- val = Interpret(context, program->branches.at(1));
- }
- else {
- val = Interpret(context, program->branches.at(2));
- }
- return val;
- }
- else if(program->type=="LessThan"){
- int32_t val;
- if(Interpret(context, program->branches.at(0)) < Interpret(context, program->branches.at(1))){
- return 1;
- }
- else {
- return 0;
- }
- }
- else{
- throw std::runtime_error("Unknown construct '"+program->type+"'");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement