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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
|
namespace Q1.core.Pipeline;
using Q1.core.Arch;
using Q1.core.Arch.Constants;
using Q1.core.Arch.Lookups;
public class Assembler
{
private Dictionary<string, AssemblerBlock> _blocks = new();
private string _currentBlock = "";
private u16 _addressOffset = 0;
public MemoryStream Assemble(TextReader source)
{
this._blocks[this._currentBlock] = new AssemblerBlock();
while (source.ReadLine() is { } line)
{
line = this.StripComments(line);
if (string.IsNullOrEmpty(line))
continue;
if (line.StartsWith('.'))
this.HandleDirective(line[1..]);
else if (line.EndsWith(':'))
this.HandleLabel(line[..^1]);
else
this.HandleInstruction(line);
}
return this.CreateFinalBinary();
}
private MemoryStream CreateFinalBinary()
{
Dictionary<string, u16> labelAddresses = new();
u16 currentAddress = this._addressOffset;
foreach ((string key, AssemblerBlock value) in this._blocks)
{
labelAddresses[key] = currentAddress;
currentAddress += (u16) value.Size;
}
MemoryStream finalBinary = new();
foreach ((_, AssemblerBlock value) in this._blocks)
{
foreach ((i64 offset, (bool word, string constant)) in value.DeferredConstants)
{
if (!labelAddresses.TryGetValue(constant, out u16 address))
throw new Exception($"Undefined label: {constant}");
if (word)
value.ResolveWordConstant((i32) offset, address);
else
value.ResolveByteConstant((i32) offset, (u8) address);
}
value.WriteToStream(finalBinary);
}
return finalBinary;
}
private void HandleDirective(string directive)
{
string[] parts = directive
.Split([' ', '\t'], StringSplitOptions.RemoveEmptyEntries)
.Select(x => x.ToLower())
.ToArray();
string directiveName = parts[0];
string[] args = parts[1..];
if (directiveName == "org")
{
if (args.Length != 1)
throw new Exception($"Expected 1 argument for .org directive, got {args.Length}");
if (args[0].StartsWith("0x"))
this._addressOffset = Convert.ToUInt16(args[0][2..], 16);
else if (args[0].StartsWith("0b"))
this._addressOffset = Convert.ToUInt16(args[0][2..], 2);
else if (i32.TryParse(args[0], out i32 decimalValue))
this._addressOffset = (u16) decimalValue;
else
throw new Exception($"Invalid argument for .org directive: {args[0]}");
}
else
throw new Exception($"Unknown directive: {directiveName}");
}
private void HandleLabel(string label)
{
this._currentBlock = label;
if (this._blocks.ContainsKey(label))
throw new Exception($"Duplicate label: {label}");
this._blocks[label] = new AssemblerBlock();
}
private void HandleInstruction(string instruction)
{
string[] parts = instruction
.Split([' ', '\t', ','], StringSplitOptions.RemoveEmptyEntries);
string opcodeName = parts[0].ToUpper();
bool isWordInstruction = !(parts.Length > 1 && parts[1].Equals("byte", StringComparison.InvariantCultureIgnoreCase));
string[] args = isWordInstruction ? parts[1..] : parts[2..];
var opcode = InstructionSet.GetOpcodeWithIndex(opcodeName, out u8 opcodeIndex);
switch (opcodeIndex)
{
case 0: // Implicit
{
if (args.Length != 0)
throw new Exception($"Expected 0 arguments for opcode {opcodeName}, got {args.Length}");
this.WriteInstruction(opcode, 0, 0, isWordInstruction);
break;
}
case 1: // Simple Addressing
{
if (args.Length != 1)
throw new Exception($"Expected 1 argument for opcode {opcodeName}, got {args.Length}");
u8 m1 = this.GetArgumentType(args[0]);
this.WriteInstruction(opcode, m1, 0, isWordInstruction);
this.WriteArgument(args[0], isWordInstruction);
break;
}
case 2: // Extended Implicit
{
if (args.Length != 0)
throw new Exception($"Expected 0 arguments for opcode {opcodeName}, got {args.Length}");
this.WriteInstruction(opcode, 0, 1, isWordInstruction);
break;
}
case 3: // Extended Addressing
{
if (args.Length != 2)
throw new Exception($"Expected 2 arguments for opcode {opcodeName}, got {args.Length}");
u8 m1 = this.GetArgumentType(args[0]);
u8 m2 = this.GetArgumentType(args[1]);
this.WriteInstruction(opcode, m1, m2, isWordInstruction);
this.WriteArgument(args[0], isWordInstruction);
this.WriteArgument(args[1], isWordInstruction);
break;
}
}
}
private void WriteInstruction(u8 opcode, u8 m1, u8 m2, bool word)
{
u16 instruction = InstructionEncoding.Encode(opcode, m1, m2, word);
this.WriteWordToBlock(instruction);
}
private u8 GetArgumentType(string arg)
{
if (arg.StartsWith('[') && arg.EndsWith(']'))
{
string inner = arg[1..^1];
if (ChipRegisters.GetRegisterIndex(inner.ToUpper()) != null)
return AddressingModes.GetAddressingMode("Register Indirect");
if (inner.Contains('+'))
return AddressingModes.GetAddressingMode("Register Indirect with Offset");
return AddressingModes.GetAddressingMode("Direct");
}
if (arg.StartsWith('@'))
{
if (arg.StartsWith("@[") && arg.EndsWith(']'))
return AddressingModes.GetAddressingMode("Indirect");
else
throw new Exception($"Invalid indirect argument format: {arg}");
}
if (ChipRegisters.GetRegisterIndex(arg.ToUpper()) != null)
return AddressingModes.GetAddressingMode("Register");
return AddressingModes.GetAddressingMode("Immediate");
}
private void WriteArgument(string arg, bool isWord)
{
if (arg.StartsWith('[') && arg.EndsWith(']'))
{
string inner = arg[1..^1];
if (ChipRegisters.GetRegisterIndex(inner.ToUpper()) is { } registerIndex)
this.WriteByteToBlock(registerIndex);
else if (inner.Contains('+'))
{
string[] parts = inner.Split('+', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length != 2)
throw new Exception($"Invalid register indirect with offset format: {arg}");
string registerPart = parts[0].Trim().ToUpper();
string offsetPart = parts[1].Trim();
if (ChipRegisters.GetRegisterIndex(registerPart) is not { } regIndex)
throw new Exception($"Invalid register in register indirect with offset: {registerPart}");
this.WriteByteToBlock(regIndex);
this.WriteConstant(offsetPart, isWord);
}
else
this.WriteConstant(inner, isWord);
}
else if (arg.StartsWith('@'))
{
if (arg.StartsWith("@[") && arg.EndsWith(']'))
{
string inner = arg[2..^1];
this.WriteConstant(inner, isWord);
}
else
throw new Exception($"Invalid indirect argument format: {arg}");
}
else if (ChipRegisters.GetRegisterIndex(arg.ToUpper()) is { } registerIndex)
this.WriteByteToBlock(registerIndex);
else
this.WriteConstant(arg, isWord);
}
private void WriteConstant(string constant, bool isWord)
{
// hex 0x0-9a-fA-F
if (constant.StartsWith("0X", StringComparison.InvariantCultureIgnoreCase))
{
string hexPart = constant[2..];
if (isWord)
this.WriteWordToBlock(Convert.ToUInt16(hexPart, 16));
else
this.WriteByteToBlock(Convert.ToByte(hexPart, 16));
}
// binary 0b0-1
else if (constant.StartsWith("0B", StringComparison.InvariantCultureIgnoreCase))
{
string binaryPart = constant[2..];
if (isWord)
this.WriteWordToBlock(Convert.ToUInt16(binaryPart, 2));
else
this.WriteByteToBlock(Convert.ToByte(binaryPart, 2));
}
// char `a, etc.
else if (constant.StartsWith('`') && constant.Length == 2)
{
char charValue = constant[1];
if (isWord)
this.WriteWordToBlock(charValue);
else
this.WriteByteToBlock((u8) charValue);
}
// decimal 0-9+
else if (i32.TryParse(constant, out i32 decimalValue))
{
if (isWord)
this.WriteWordToBlock((u16) decimalValue);
else
this.WriteByteToBlock((u8) decimalValue);
}
// label
else
{
if (isWord)
this.DeferWriteWordToBlock(constant);
else
this.DeferWriteByteToBlock(constant);
}
}
private void WriteByteToBlock(u8 data)
{
this._blocks[this._currentBlock].WriteByte(data);
}
private void WriteWordToBlock(u16 data)
{
this._blocks[this._currentBlock].WriteWord(data);
}
private void DeferWriteByteToBlock(string constant)
{
this._blocks[this._currentBlock].DeferByteConstant(constant);
}
private void DeferWriteWordToBlock(string constant)
{
this._blocks[this._currentBlock].DeferWordConstant(constant);
}
private string StripComments(string line)
{
int commentIndex = line.IndexOf(';');
if (commentIndex >= 0)
return line[..commentIndex].Trim();
return line.Trim();
}
}
|