-
Notifications
You must be signed in to change notification settings - Fork 0
/
VMWriter.cs
88 lines (74 loc) · 2.27 KB
/
VMWriter.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
using System;
using System.IO;
using System.Collections.Generic;
namespace JackCompiler
{
enum Segment { CONST, ARG, LOCAL, STATIC, THIS, THAT, POINTER, TEMP };
enum Command { ADD, SUB, NEG, EQ, GT, LT, AND, OR, NOT };
/// <summary>
/// Writes the virtual machine code.
/// </summary>
class VMWriter
{
List<string> vmCommands = new List<string>();
const string VMFileExtension = ".vm";
public void WritePush(Segment segment, int index)
{
string seg = Enum.GetName(typeof(Segment), segment).ToLower();
if(seg == "const")
seg = "constant";
else if(seg == "arg")
seg = "argument";
vmCommands.Add("push " + seg + " " + index);
}
public void WritePop(Segment segment, int index)
{
string seg = Enum.GetName(typeof(Segment), segment).ToLower();
if(seg == "const")
seg = "constant";
else if(seg == "arg")
seg = "argument";
vmCommands.Add("pop " + seg + " " + index);
}
public void WriteArithmetic(Command command)
{
vmCommands.Add(Enum.GetName(typeof(Command), command).ToLower());
}
public void WriteLabel(string label)
{
vmCommands.Add("label " + label);
}
public void WriteGoto(string label)
{
vmCommands.Add("goto " + label);
}
public void WriteIf(string label)
{
vmCommands.Add("if-goto " + label);
}
public void WriteCall(string name, int nArgs)
{
vmCommands.Add("call " + name + " " + nArgs);
}
public void WriteFunction(string name, int nLocals)
{
vmCommands.Add("function " + name + " " + nLocals);
}
public void WriteReturn()
{
vmCommands.Add("return");
}
public void Close(string path)
{
try
{
string filePath = path.Split('.')[0] + VMFileExtension;
File.WriteAllLines(filePath, vmCommands);
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}