package cmaj7.tree;

import java.util.LinkedList;
import java.util.List;

import cmaj7.vm.Instruction;
import cmaj7.vm.Instruction.Instr;

public class GenCode implements Visitor<Void> {
	public List<Instruction> result=new LinkedList<>();

	@Override
	public Void visit(BinOpExp node) {
		node.lhs.welcome(this);
		node.rhs.welcome(this);
		result.add(node.op.getInstruction());
		return null;
	}

	@Override
	public Void visit(IntLiteral node) {
		result.add(new Instruction(Instruction.Instr.PUSHINT,node.n));
		return null;
	}

	@Override
	public Void visit(Variable node) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Void visit(IfExpr ifExpr) {
		ifExpr.cond.welcome(this);
		int oldSize = result.size();
		Instruction theJump 
		 = new Instruction(Instr.JMPIFNONZERO, 0);
		result.add(theJump);
		ifExpr.alt2.welcome(this);
		theJump.arg1 = result.size()-oldSize+1;
		
		Instruction theSecondJump 
		 = new Instruction(Instr.JUMP, 0);
		result.add(theSecondJump);
		int secondOldSize = result.size();
		ifExpr.alt1.welcome(this);
		theSecondJump.arg1=result.size()-secondOldSize+1;
		
		
		
		return null;
	}

}
