view LightClone/Source/VirtualMachine.h @ 54:95677f648a2c VirtualMachine Mk2

Refactored VirtualMachine
author koryspansel
date Fri, 30 Sep 2011 18:37:54 -0700
parents 7e3a0ae9c016
children
line wrap: on
line source

/*
 * VirtualMachine.h
 */

#ifndef __VIRTUALMACHINE_H__
#define __VIRTUALMACHINE_H__

#include "Core.h"
#include "PoolAllocator.h"

/*
 * Instruction
 */
enum
{
	Instruction_Nop,
	Instruction_Action,
	Instruction_Call,
	Instruction_Return,
};

/*
 * VirtualMachine
 */
class VirtualMachine
{
	/*
	 * Capacity
	 */
	static const uint32 Capacity = 1024;

	/*
	 * Frame
	 *	The frame holds the current execution context, which includes the
	 *	starting address of the function and its continuation.
	 */
	struct Frame
	{
		/*
		 * nFunction
		 *	Memory address of the currently executing function
		 */
		uint32 nAddress;

		/*
		 * nContinuation
		 *	Memory address of the current function's continuation
		 */
		uint32 nContinuation;

		/*
		 * pLast
		 *	Pointer to the previous call frame
		 */
		Frame* pLast;
	};

	/*
	 * FrameAllocator
	 */
	typedef PoolAllocator<Frame, 16> FrameAllocator;

	/*
	 * nMemory
	 *	Define the memory layout for each possible function.  The 
	 *	additional instruction is used to implement function 
	 *	continuations.
	 */
	uint8 nMemory[Capacity];

	/*
	 * nInstructionPointer
	 *	Points to the instruction currently being executed.  The value
	 *	can be decoded into a function index and instruction offset
	 */
	uint32 nInstructionPointer;

	/*
	 * pFrame
	 */
	Frame* pFrame;

	/*
	 * kFrameAllocator
	 */
	FrameAllocator kFrameAllocator;

public:

	/*
	 * VirtualMachine
	 */
	VirtualMachine();

	/*
	 * Step
	 */
	uint32 Step();

	/*
	 * Reset
	 */
	void Reset();

	/*
	 * Clear
	 */
	void Clear();

	/*
	 * GetMemorySize
	 */
	uint32 GetMemorySize() const;

	/*
	 * GetMemoryPointer
	 */
	uint8* GetMemoryPointer();

private:

	/*
	 * Advance
	 */
	uint8 Advance()
	{
		return nMemory[nInstructionPointer++];
	}

	/*
	 * PushFrame
	 */
	void PushFrame(uint32 nFunctionAddress, uint32 nContinuationAddress);

	/*
	 * PopFrame
	 */
	void PopFrame();

};

#endif //__VIRTUALMACHINE_H__