Full Code of parrt/simple-virtual-machine for AI

shatter-stack 82a6f4716696 cached
10 files
25.0 KB
7.3k tokens
18 symbols
1 requests
Download .txt
Repository: parrt/simple-virtual-machine
Branch: shatter-stack
Commit: 82a6f4716696
Files: 10
Total size: 25.0 KB

Directory structure:
gitextract_oxlhz3h_/

├── .gitignore
├── LICENSE
├── README.md
├── simple-virtual-machine.iml
├── simple-virtual-machine.ipr
└── src/
    └── vm/
        ├── Bytecode.java
        ├── Context.java
        ├── FuncMetaData.java
        ├── Test.java
        └── VM.java

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
*.class

# Mobile Tools for Java (J2ME)
.mtj.tmp/

# Package Files #
*.jar
*.war
*.ear

# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*


================================================
FILE: LICENSE
================================================
Copyright (c) 2014, Terence Parr
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

* Neither the name of the {organization} nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

================================================
FILE: README.md
================================================
simple-virtual-machine
======================

A simple VM for a talk on building VMs in Java. See [video](https://www.youtube.com/watch?v=OjaAToVkoTw) and [slides](http://www.slideshare.net/parrt/how-to-build-a-virtual-machine).

There are multiple branches:

* [master](https://github.com/parrt/simple-virtual-machine). Basic instructions only (no function calls).
* [add-functions](https://github.com/parrt/simple-virtual-machine/tree/add-functions). Includes CALL/RET instructions, runs factorial test function.
* [split-stack](https://github.com/parrt/simple-virtual-machine/tree/split-stack). Split into operand stack and function call stack.
* [func-meta-info](https://github.com/parrt/simple-virtual-machine/tree/func-meta-info).  CALL bytecode instruction takes an index into a metadata table for functions rather than an address and the number of arguments. This makes it much easier for bytecode compiler to generate code because it doesn't need to worry about forward references. This branch also properly allocates space for local variables.
* [shatter-stack](https://github.com/parrt/simple-virtual-machine/tree/shatter-stack). Broke apart the `Context[]` stack into a linked-list with `invokingContext` as parent pointer to caller. added call stack for trace.

See also a [C version derived from split-stack](https://github.com/parrt/simple-virtual-machine-C). Parts derived from [codyebberson's C implementation](https://github.com/codyebberson/vm).


================================================
FILE: simple-virtual-machine.iml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
  <component name="NewModuleRootManager" inherit-compiler-output="true">
    <exclude-output />
    <content url="file://$MODULE_DIR$">
      <sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
    </content>
    <orderEntry type="inheritedJdk" />
    <orderEntry type="sourceFolder" forTests="false" />
  </component>
</module>



================================================
FILE: simple-virtual-machine.ipr
================================================
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="CompilerConfiguration">
    <wildcardResourcePatterns>
      <entry name="!?*.java" />
      <entry name="!?*.form" />
      <entry name="!?*.class" />
      <entry name="!?*.groovy" />
      <entry name="!?*.scala" />
      <entry name="!?*.flex" />
      <entry name="!?*.kt" />
      <entry name="!?*.clj" />
    </wildcardResourcePatterns>
  </component>
  <component name="CopyrightManager" default="" />
  <component name="DependencyValidationManager">
    <option name="SKIP_IMPORT_STATEMENTS" value="false" />
  </component>
  <component name="Encoding" useUTFGuessing="true" native2AsciiForPropertiesFiles="false" />
  <component name="IdProvider" IDEtalkID="97D7DBFBCE4D11CA285C5356222AF1E5" />
  <component name="InspectionProjectProfileManager">
    <profile version="1.0">
      <option name="myName" value="Project Default" />
    </profile>
    <version value="1.0" />
  </component>
  <component name="KotlinCommonCompilerArguments">
    <option name="languageVersion" value="1.1" />
    <option name="apiVersion" value="1.1" />
  </component>
  <component name="Palette2">
    <group name="Swing">
      <item class="com.intellij.uiDesigner.HSpacer" tooltip-text="Horizontal Spacer" icon="/com/intellij/uiDesigner/icons/hspacer.png" removable="false" auto-create-binding="false" can-attach-label="false">
        <default-constraints vsize-policy="1" hsize-policy="6" anchor="0" fill="1" />
      </item>
      <item class="com.intellij.uiDesigner.VSpacer" tooltip-text="Vertical Spacer" icon="/com/intellij/uiDesigner/icons/vspacer.png" removable="false" auto-create-binding="false" can-attach-label="false">
        <default-constraints vsize-policy="6" hsize-policy="1" anchor="0" fill="2" />
      </item>
      <item class="javax.swing.JPanel" icon="/com/intellij/uiDesigner/icons/panel.png" removable="false" auto-create-binding="false" can-attach-label="false">
        <default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3" />
      </item>
      <item class="javax.swing.JScrollPane" icon="/com/intellij/uiDesigner/icons/scrollPane.png" removable="false" auto-create-binding="false" can-attach-label="true">
        <default-constraints vsize-policy="7" hsize-policy="7" anchor="0" fill="3" />
      </item>
      <item class="javax.swing.JButton" icon="/com/intellij/uiDesigner/icons/button.png" removable="false" auto-create-binding="true" can-attach-label="false">
        <default-constraints vsize-policy="0" hsize-policy="3" anchor="0" fill="1" />
        <initial-values>
          <property name="text" value="Button" />
        </initial-values>
      </item>
      <item class="javax.swing.JRadioButton" icon="/com/intellij/uiDesigner/icons/radioButton.png" removable="false" auto-create-binding="true" can-attach-label="false">
        <default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
        <initial-values>
          <property name="text" value="RadioButton" />
        </initial-values>
      </item>
      <item class="javax.swing.JCheckBox" icon="/com/intellij/uiDesigner/icons/checkBox.png" removable="false" auto-create-binding="true" can-attach-label="false">
        <default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
        <initial-values>
          <property name="text" value="CheckBox" />
        </initial-values>
      </item>
      <item class="javax.swing.JLabel" icon="/com/intellij/uiDesigner/icons/label.png" removable="false" auto-create-binding="false" can-attach-label="false">
        <default-constraints vsize-policy="0" hsize-policy="0" anchor="8" fill="0" />
        <initial-values>
          <property name="text" value="Label" />
        </initial-values>
      </item>
      <item class="javax.swing.JTextField" icon="/com/intellij/uiDesigner/icons/textField.png" removable="false" auto-create-binding="true" can-attach-label="true">
        <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
          <preferred-size width="150" height="-1" />
        </default-constraints>
      </item>
      <item class="javax.swing.JPasswordField" icon="/com/intellij/uiDesigner/icons/passwordField.png" removable="false" auto-create-binding="true" can-attach-label="true">
        <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
          <preferred-size width="150" height="-1" />
        </default-constraints>
      </item>
      <item class="javax.swing.JFormattedTextField" icon="/com/intellij/uiDesigner/icons/formattedTextField.png" removable="false" auto-create-binding="true" can-attach-label="true">
        <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
          <preferred-size width="150" height="-1" />
        </default-constraints>
      </item>
      <item class="javax.swing.JTextArea" icon="/com/intellij/uiDesigner/icons/textArea.png" removable="false" auto-create-binding="true" can-attach-label="true">
        <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
          <preferred-size width="150" height="50" />
        </default-constraints>
      </item>
      <item class="javax.swing.JTextPane" icon="/com/intellij/uiDesigner/icons/textPane.png" removable="false" auto-create-binding="true" can-attach-label="true">
        <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
          <preferred-size width="150" height="50" />
        </default-constraints>
      </item>
      <item class="javax.swing.JEditorPane" icon="/com/intellij/uiDesigner/icons/editorPane.png" removable="false" auto-create-binding="true" can-attach-label="true">
        <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
          <preferred-size width="150" height="50" />
        </default-constraints>
      </item>
      <item class="javax.swing.JComboBox" icon="/com/intellij/uiDesigner/icons/comboBox.png" removable="false" auto-create-binding="true" can-attach-label="true">
        <default-constraints vsize-policy="0" hsize-policy="2" anchor="8" fill="1" />
      </item>
      <item class="javax.swing.JTable" icon="/com/intellij/uiDesigner/icons/table.png" removable="false" auto-create-binding="true" can-attach-label="false">
        <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
          <preferred-size width="150" height="50" />
        </default-constraints>
      </item>
      <item class="javax.swing.JList" icon="/com/intellij/uiDesigner/icons/list.png" removable="false" auto-create-binding="true" can-attach-label="false">
        <default-constraints vsize-policy="6" hsize-policy="2" anchor="0" fill="3">
          <preferred-size width="150" height="50" />
        </default-constraints>
      </item>
      <item class="javax.swing.JTree" icon="/com/intellij/uiDesigner/icons/tree.png" removable="false" auto-create-binding="true" can-attach-label="false">
        <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
          <preferred-size width="150" height="50" />
        </default-constraints>
      </item>
      <item class="javax.swing.JTabbedPane" icon="/com/intellij/uiDesigner/icons/tabbedPane.png" removable="false" auto-create-binding="true" can-attach-label="false">
        <default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
          <preferred-size width="200" height="200" />
        </default-constraints>
      </item>
      <item class="javax.swing.JSplitPane" icon="/com/intellij/uiDesigner/icons/splitPane.png" removable="false" auto-create-binding="false" can-attach-label="false">
        <default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
          <preferred-size width="200" height="200" />
        </default-constraints>
      </item>
      <item class="javax.swing.JSpinner" icon="/com/intellij/uiDesigner/icons/spinner.png" removable="false" auto-create-binding="true" can-attach-label="true">
        <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
      </item>
      <item class="javax.swing.JSlider" icon="/com/intellij/uiDesigner/icons/slider.png" removable="false" auto-create-binding="true" can-attach-label="false">
        <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
      </item>
      <item class="javax.swing.JSeparator" icon="/com/intellij/uiDesigner/icons/separator.png" removable="false" auto-create-binding="false" can-attach-label="false">
        <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3" />
      </item>
      <item class="javax.swing.JProgressBar" icon="/com/intellij/uiDesigner/icons/progressbar.png" removable="false" auto-create-binding="true" can-attach-label="false">
        <default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1" />
      </item>
      <item class="javax.swing.JToolBar" icon="/com/intellij/uiDesigner/icons/toolbar.png" removable="false" auto-create-binding="false" can-attach-label="false">
        <default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1">
          <preferred-size width="-1" height="20" />
        </default-constraints>
      </item>
      <item class="javax.swing.JToolBar$Separator" icon="/com/intellij/uiDesigner/icons/toolbarSeparator.png" removable="false" auto-create-binding="false" can-attach-label="false">
        <default-constraints vsize-policy="0" hsize-policy="0" anchor="0" fill="1" />
      </item>
      <item class="javax.swing.JScrollBar" icon="/com/intellij/uiDesigner/icons/scrollbar.png" removable="false" auto-create-binding="true" can-attach-label="false">
        <default-constraints vsize-policy="6" hsize-policy="0" anchor="0" fill="2" />
      </item>
    </group>
  </component>
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/simple-virtual-machine.iml" filepath="$PROJECT_DIR$/simple-virtual-machine.iml" />
    </modules>
  </component>
  <component name="ProjectRootManager" version="2" languageLevel="JDK_1_6" default="false" project-jdk-name="1.8" project-jdk-type="JavaSDK">
    <output url="file://$PROJECT_DIR$/out" />
  </component>
  <component name="VcsDirectoryMappings">
    <mapping directory="" vcs="Git" />
  </component>
</project>

================================================
FILE: src/vm/Bytecode.java
================================================
package vm;

public class Bytecode {
	public static class Instruction {
		String name; // E.g., "iadd", "call"
		int n = 0;
		public Instruction(String name) { this(name,0); }
		public Instruction(String name, int nargs) {
			this.name = name;
			this.n = nargs;
		}
	}

	// INSTRUCTION BYTECODES (byte is signed; use a short to keep 0..255)
	public static final short IADD = 1;     // int add
	public static final short ISUB = 2;
	public static final short IMUL = 3;
	public static final short ILT  = 4;     // int less than
	public static final short IEQ  = 5;     // int equal
	public static final short BR   = 6;     // branch
	public static final short BRT  = 7;     // branch if true
	public static final short BRF  = 8;     // branch if true
	public static final short ICONST = 9;   // push constant integer
	public static final short LOAD   = 10;  // load from local context
	public static final short GLOAD  = 11;  // load from global memory
	public static final short STORE  = 12;  // store in local context
	public static final short GSTORE = 13;  // store in global memory
	public static final short PRINT  = 14;  // print stack top
	public static final short POP  = 15;    // throw away top of stack
	public static final short CALL = 16;
	public static final short RET  = 17;    // return with/without value

	public static final short HALT = 18;

	public static Instruction[] instructions = new Instruction[] {
		null, // <INVALID>
		new Instruction("iadd"), // index is the opcode
		new Instruction("isub"),
		new Instruction("imul"),
		new Instruction("ilt"),
		new Instruction("ieq"),
		new Instruction("br", 1),
		new Instruction("brt", 1),
		new Instruction("brf", 1),
		new Instruction("iconst", 1),
		new Instruction("load", 1),
		new Instruction("gload", 1),
		new Instruction("store", 1),
		new Instruction("gstore", 1),
		new Instruction("print"),
		new Instruction("pop"),
		new Instruction("call", 1), // call index of function in meta-info table
		new Instruction("ret"),
		new Instruction("halt")
	};
}


================================================
FILE: src/vm/Context.java
================================================
package vm;

/** To call, push one of these and pop to return */
public class Context {
	Context invokingContext;	// parent in the stack or "caller"
	FuncMetaData metadata;		// info about function we're executing
	int returnip;
	int[] locals; // args + locals, indexed from 0

	public Context(Context invokingContext, int returnip, FuncMetaData metadata) {
		this.invokingContext = invokingContext;
		this.returnip = returnip;
		this.metadata = metadata;
		locals = new int[metadata.nargs+metadata.nlocals];
	}
}


================================================
FILE: src/vm/FuncMetaData.java
================================================
package vm;

public class FuncMetaData {
	public String name;
	public int nargs;
	public int nlocals;
	public int address; // bytecode address

	public FuncMetaData(String name, int nargs, int nlocals, int address) {
		this.name = name;
		this.nargs = nargs;
		this.nlocals = nlocals;
		this.address = address;
	}
}


================================================
FILE: src/vm/Test.java
================================================
package vm;

import static vm.Bytecode.BR;
import static vm.Bytecode.BRF;
import static vm.Bytecode.CALL;
import static vm.Bytecode.GLOAD;
import static vm.Bytecode.GSTORE;
import static vm.Bytecode.HALT;
import static vm.Bytecode.IADD;
import static vm.Bytecode.ICONST;
import static vm.Bytecode.ILT;
import static vm.Bytecode.IMUL;
import static vm.Bytecode.ISUB;
import static vm.Bytecode.LOAD;
import static vm.Bytecode.PRINT;
import static vm.Bytecode.RET;
import static vm.Bytecode.STORE;

public class Test {
	static int[] hello = {
		ICONST, 1,
		ICONST, 2,
		IADD,
		PRINT,
		HALT
	};

	static int[] loop = {
	// .GLOBALS 2; N, I
	// N = 10						ADDRESS
			ICONST, 10,				// 0
			GSTORE, 0,				// 2
	// I = 0
			ICONST, 0,				// 4
			GSTORE, 1,				// 6
	// WHILE I<N:
	// START (8):
			GLOAD, 1,				// 8
			GLOAD, 0,				// 10
			ILT,					// 12
			BRF, 24,				// 13
	//     I = I + 1
			GLOAD, 1,				// 15
			ICONST, 1,				// 17
			IADD,					// 19
			GSTORE, 1,				// 20
			BR, 8,					// 22
	// DONE (24):
	// PRINT "LOOPED "+N+" TIMES."
			HALT					// 24
	};
	static FuncMetaData[] loop_metadata = {
		new FuncMetaData("main", 0, 0, 0)
	};

	static int FACTORIAL_INDEX = 1;
	static int FACTORIAL_ADDRESS = 0;
	static int MAIN_ADDRESS = 21;
	static int[] factorial = {
//.def factorial: ARGS=1, LOCALS=0	ADDRESS
//	IF N < 2 RETURN 1
			LOAD, 0,				// 0
			ICONST, 2,				// 2
			ILT,					// 4
			BRF, 10,				// 5
			ICONST, 1,				// 7
			RET,					// 9
//CONT:
//	RETURN N * FACT(N-1)
			LOAD, 0,				// 10
			LOAD, 0,				// 12
			ICONST, 1,				// 14
			ISUB,					// 16
			CALL, FACTORIAL_INDEX,	// 17
			IMUL,					// 19
			RET,					// 20
//.DEF MAIN: ARGS=0, LOCALS=0
// PRINT FACT(1)
			ICONST, 5,				// 21    <-- MAIN METHOD!
			CALL, FACTORIAL_INDEX,	// 23
			PRINT,					// 25
			HALT					// 26
	};
	static FuncMetaData[] factorial_metadata = {
		//.def factorial: ARGS=1, LOCALS=0	ADDRESS
		new FuncMetaData("main", 0, 0, MAIN_ADDRESS),
		new FuncMetaData("factorial", 1, 0, FACTORIAL_ADDRESS)
	};

	static int[] f = {
	//								ADDRESS
	//.def main() { print f(10); }
		ICONST, 10,					// 0
		CALL, 1,					// 2
		PRINT,						// 4
		HALT,						// 5
	//.def f(x): ARGS=1, LOCALS=1
	//  a = x;
		LOAD, 0,					// 6	<-- start of f
		STORE, 1,
	// return 2*a
		LOAD, 1,
		ICONST, 2,
		IMUL,
		RET
	};
	static FuncMetaData[] f_metadata = {
		new FuncMetaData("main", 0, 0, 0),
		new FuncMetaData("f", 1, 1, 6)
	};


	public static void main(String[] args) {
		VM vm = new VM(factorial, 0, factorial_metadata);
		vm.trace = true;
		vm.exec(factorial_metadata[0].address);

		vm = new VM(f, 2, f_metadata);
		vm.exec(f_metadata[0].address);
		vm.dumpDataMemory();

		vm = new VM(loop, 2, loop_metadata);
		vm.exec(loop_metadata[0].address);
	}
}


================================================
FILE: src/vm/VM.java
================================================
package vm;

import java.util.ArrayList;
import java.util.List;

import static vm.Bytecode.BR;
import static vm.Bytecode.BRF;
import static vm.Bytecode.BRT;
import static vm.Bytecode.CALL;
import static vm.Bytecode.GLOAD;
import static vm.Bytecode.GSTORE;
import static vm.Bytecode.HALT;
import static vm.Bytecode.IADD;
import static vm.Bytecode.ICONST;
import static vm.Bytecode.IEQ;
import static vm.Bytecode.ILT;
import static vm.Bytecode.IMUL;
import static vm.Bytecode.ISUB;
import static vm.Bytecode.LOAD;
import static vm.Bytecode.POP;
import static vm.Bytecode.PRINT;
import static vm.Bytecode.RET;
import static vm.Bytecode.STORE;

/** A simple stack-based interpreter */
public class VM {
	public static final int DEFAULT_STACK_SIZE = 1000;
	public static final int DEFAULT_CALL_STACK_SIZE = 1000;
	public static final int FALSE = 0;
	public static final int TRUE = 1;

	// registers
	int ip;             // instruction pointer register
	int sp = -1;  		// stack pointer register

	// memory
	int[] code;         // word-addressable code memory but still bytecodes.
	int[] globals;      // global variable space
	int[] stack;		// Operand stack, grows upwards
	Context ctx;		// the active context

	/** Metadata about the functions allows us to refer to functions by
	 * 	their index in this table. It makes code generation easier for
	 * 	the bytecode compiler because it doesn't have to resolve
	 *  addresses for forward references. It can generate simply
	 *  "CALL i" where i is the index of the function. Later, the
	 *  compiler can store the function address in the metadata table
	 *  when the code is generated for that function.
	 */
	FuncMetaData[] metadata;

	public boolean trace = false;

	public VM(int[] code, int nglobals, FuncMetaData[] metadata) {
		this.code = code;
		globals = new int[nglobals];
		stack = new int[DEFAULT_STACK_SIZE];
		this.metadata = metadata;
	}

	public void exec(int startip) {
		ip = startip;
		ctx = new Context(null,0,metadata[0]); // simulate a call to main()
		cpu();
	}

	/** Simulate the fetch-decode execute cycle */
	protected void cpu() {
		int opcode = code[ip];
		int a,b,addr,regnum;
		while (opcode!= HALT && ip < code.length) {
			if ( trace ) System.err.printf("%-35s", disInstr());
			ip++; //jump to next instruction or to operand
			switch (opcode) {
				case IADD:
					b = stack[sp--];   			// 2nd opnd at top of stack
					a = stack[sp--]; 			// 1st opnd 1 below top
					stack[++sp] = a + b;      	// push result
					break;
				case ISUB:
					b = stack[sp--];
					a = stack[sp--];
					stack[++sp] = a - b;
					break;
				case IMUL:
					b = stack[sp--];
					a = stack[sp--];
					stack[++sp] = a * b;
					break;
				case ILT :
					b = stack[sp--];
					a = stack[sp--];
					stack[++sp] = (a < b) ? TRUE : FALSE;
					break;
				case IEQ :
					b = stack[sp--];
					a = stack[sp--];
					stack[++sp] = (a == b) ? TRUE : FALSE;
					break;
				case BR :
					ip = code[ip++];
					break;
				case BRT :
					addr = code[ip++];
					if ( stack[sp--]==TRUE ) ip = addr;
					break;
				case BRF :
					addr = code[ip++];
					if ( stack[sp--]==FALSE ) ip = addr;
					break;
				case ICONST:
					stack[++sp] = code[ip++]; // push operand
					break;
				case LOAD : // load local or arg
					regnum = code[ip++];
					stack[++sp] = ctx.locals[regnum];
					break;
				case GLOAD :// load from global memory
					addr = code[ip++];
					stack[++sp] = globals[addr];
					break;
				case STORE :
					regnum = code[ip++];
					ctx.locals[regnum] = stack[sp--];
					break;
				case GSTORE :
					addr = code[ip++];
					globals[addr] = stack[sp--];
					break;
				case PRINT :
					System.out.println(stack[sp--]);
					break;
				case POP:
					--sp;
					break;
				case CALL :
					// expects all args on stack
					int findex = code[ip++];			// index of target function
					int nargs = metadata[findex].nargs;	// how many args got pushed
					ctx = new Context(ctx,ip,metadata[findex]);
					// copy args into new context
					int firstarg = sp-nargs+1;
					for (int i=0; i<nargs; i++) {
						ctx.locals[i] = stack[firstarg+i];
					}
					sp -= nargs;
					ip = metadata[findex].address;		// jump to function
					break;
				case RET:
					ip = ctx.returnip;
					ctx = ctx.invokingContext;			// pop
					break;
				default :
					throw new Error("invalid opcode: "+opcode+" at ip="+(ip-1));
			}
			if ( trace ) System.err.printf("%-22s %s\n", stackString(), callStackString());
			opcode = code[ip];
		}
		if ( trace ) System.err.printf("%-35s", disInstr());
		if ( trace ) System.err.println(stackString());
		if ( trace ) dumpDataMemory();
	}

	protected String stackString() {
		StringBuilder buf = new StringBuilder();
		buf.append("stack=[");
		for (int i = 0; i <= sp; i++) {
			int o = stack[i];
			buf.append(" ");
			buf.append(o);
		}
		buf.append(" ]");
		return buf.toString();
	}

	protected String callStackString() {
		List<String> stack = new ArrayList<String>();
		Context c = ctx;
		while ( c!=null ) {
			if ( c.metadata!=null ) {
				stack.add(0, c.metadata.name);
			}
			c = c.invokingContext;
		}
		return "calls="+stack.toString();
	}

	protected String disInstr() {
		int opcode = code[ip];
		String opName = Bytecode.instructions[opcode].name;
		StringBuilder buf = new StringBuilder();
		buf.append(String.format("%04d:\t%-11s", ip, opName));
		int nargs = Bytecode.instructions[opcode].n;
		if ( opcode==CALL ) {
			buf.append(metadata[code[ip+1]].name);
		}
		else if ( nargs>0 ) {
			List<String> operands = new ArrayList<String>();
			for (int i=ip+1; i<=ip+nargs; i++) {
				operands.add(String.valueOf(code[i]));
			}
			for (int i = 0; i<operands.size(); i++) {
				String s = operands.get(i);
				if ( i>0 ) buf.append(", ");
				buf.append(s);
			}
		}
		return buf.toString();
	}

	protected void dumpDataMemory() {
		System.err.println("Data memory:");
		int addr = 0;
		for (int o : globals) {
			System.err.printf("%04d: %s\n", addr, o);
			addr++;
		}
		System.err.println();
	}
}
Download .txt
gitextract_oxlhz3h_/

├── .gitignore
├── LICENSE
├── README.md
├── simple-virtual-machine.iml
├── simple-virtual-machine.ipr
└── src/
    └── vm/
        ├── Bytecode.java
        ├── Context.java
        ├── FuncMetaData.java
        ├── Test.java
        └── VM.java
Download .txt
SYMBOL INDEX (18 symbols across 5 files)

FILE: src/vm/Bytecode.java
  class Bytecode (line 3) | public class Bytecode {
    class Instruction (line 4) | public static class Instruction {
      method Instruction (line 7) | public Instruction(String name) { this(name,0); }
      method Instruction (line 8) | public Instruction(String name, int nargs) {

FILE: src/vm/Context.java
  class Context (line 4) | public class Context {
    method Context (line 10) | public Context(Context invokingContext, int returnip, FuncMetaData met...

FILE: src/vm/FuncMetaData.java
  class FuncMetaData (line 3) | public class FuncMetaData {
    method FuncMetaData (line 9) | public FuncMetaData(String name, int nargs, int nlocals, int address) {

FILE: src/vm/Test.java
  class Test (line 19) | public class Test {
    method main (line 113) | public static void main(String[] args) {

FILE: src/vm/VM.java
  class VM (line 26) | public class VM {
    method VM (line 54) | public VM(int[] code, int nglobals, FuncMetaData[] metadata) {
    method exec (line 61) | public void exec(int startip) {
    method cpu (line 68) | protected void cpu() {
    method stackString (line 164) | protected String stackString() {
    method callStackString (line 176) | protected String callStackString() {
    method disInstr (line 188) | protected String disInstr() {
    method dumpDataMemory (line 211) | protected void dumpDataMemory() {
Condensed preview — 10 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (29K chars).
[
  {
    "path": ".gitignore",
    "chars": 189,
    "preview": "*.class\n\n# Mobile Tools for Java (J2ME)\n.mtj.tmp/\n\n# Package Files #\n*.jar\n*.war\n*.ear\n\n# virtual machine crash logs, se"
  },
  {
    "path": "LICENSE",
    "chars": 1487,
    "preview": "Copyright (c) 2014, Terence Parr\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or withou"
  },
  {
    "path": "README.md",
    "chars": 1466,
    "preview": "simple-virtual-machine\n======================\n\nA simple VM for a talk on building VMs in Java. See [video](https://www.y"
  },
  {
    "path": "simple-virtual-machine.iml",
    "chars": 425,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<module type=\"JAVA_MODULE\" version=\"4\">\n  <component name=\"NewModuleRootManager\" "
  },
  {
    "path": "simple-virtual-machine.ipr",
    "chars": 10383,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project version=\"4\">\n  <component name=\"CompilerConfiguration\">\n    <wildcardRes"
  },
  {
    "path": "src/vm/Bytecode.java",
    "chars": 2031,
    "preview": "package vm;\n\npublic class Bytecode {\n\tpublic static class Instruction {\n\t\tString name; // E.g., \"iadd\", \"call\"\n\t\tint n ="
  },
  {
    "path": "src/vm/Context.java",
    "chars": 513,
    "preview": "package vm;\n\n/** To call, push one of these and pop to return */\npublic class Context {\n\tContext invokingContext;\t// par"
  },
  {
    "path": "src/vm/FuncMetaData.java",
    "chars": 316,
    "preview": "package vm;\n\npublic class FuncMetaData {\n\tpublic String name;\n\tpublic int nargs;\n\tpublic int nlocals;\n\tpublic int addres"
  },
  {
    "path": "src/vm/Test.java",
    "chars": 2749,
    "preview": "package vm;\n\nimport static vm.Bytecode.BR;\nimport static vm.Bytecode.BRF;\nimport static vm.Bytecode.CALL;\nimport static "
  },
  {
    "path": "src/vm/VM.java",
    "chars": 6015,
    "preview": "package vm;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport static vm.Bytecode.BR;\nimport static vm.Bytecode"
  }
]

About this extraction

This page contains the full source code of the parrt/simple-virtual-machine GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 10 files (25.0 KB), approximately 7.3k tokens, and a symbol index with 18 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!