-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompiler.js
More file actions
456 lines (377 loc) · 15.7 KB
/
Copy pathcompiler.js
File metadata and controls
456 lines (377 loc) · 15.7 KB
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
function ADD(rd, rs, rt) {
return Number("0b000000" + "00000" + rd.toString(2).padStart(5, "0") + rs.toString(2).padStart(5, "0") + rt.toString(2).padStart(5, "0") + "000000");
}
function SUB(rd, rs, rt) {
return Number("0b000000" + "00001" + rd.toString(2).padStart(5, "0") + rs.toString(2).padStart(5, "0") + rt.toString(2).padStart(5, "0") + "000000");
}
function LSL(rd, rs, rt) {
return Number("0b000000" + "00010" + rd.toString(2).padStart(5, "0") + rs.toString(2).padStart(5, "0") + rt.toString(2).padStart(5, "0") + "000000");
}
function OR(rd, rs, rt) {
return Number("0b000000" + "00011" + rd.toString(2).padStart(5, "0") + rs.toString(2).padStart(5, "0") + rt.toString(2).padStart(5, "0") + "000000");
}
function MUL(rd, rs, rt) {
return Number("0b000000" + "00110" + rd.toString(2).padStart(5, "0") + rs.toString(2).padStart(5, "0") + rt.toString(2).padStart(5, "0") + "000000");
}
function DIV(rd, rs, rt) {
return Number("0b000000" + "00101" + rd.toString(2).padStart(5, "0") + rs.toString(2).padStart(5, "0") + rt.toString(2).padStart(5, "0") + "000000");
}
function MOD(rd, rs, rt) {
return Number("0b000000" + "00100" + rd.toString(2).padStart(5, "0") + rs.toString(2).padStart(5, "0") + rt.toString(2).padStart(5, "0") + "000000");
}
function LW(rd, rs, imm16) {
return Number("0b100011" + rd.toString(2).padStart(5, "0") + rs.toString(2).padStart(5, "0") + imm16.toString(2).padStart(16, "0"));
}
function SW(rd, rs, imm16) {
return Number("0b101011" + rd.toString(2).padStart(5, "0") + rs.toString(2).padStart(5, "0") + imm16.toString(2).padStart(16, "0"));
}
function BEQ(rs, rt, imm16) {
return Number("0b000011" + rs.toString(2).padStart(5, "0") + rt.toString(2).padStart(5, "0") + imm16.toString(2).padStart(16, "0"));
}
function JMP(imm26) {
return Number("0b000010" + imm26.toString(2).padStart(26, "0"));
}
function HLT() {
return Number("0b111111" + "".padStart(26, 0));
}
function CLR(rd) {
return Number("0b111110" + rd.toString(2).padStart(5, "0") + "".padStart(21, "0"));
}
function LDR(rd, imm21) {
return Number("0b101101" + rd.toString(2).padStart(5, "0") + imm21.toString(2).padStart(21, "0"));
}
// console.log("0: LDR 0,52: ", LDR(0, 52).toString(16), (52).toString(16)); // 0
// console.log("1: LDR 1,46: ", LDR(1, 46).toString(16), (46).toString(16)); // 1
// console.log("2: LDR 7,2: ", LDR(7, 2).toString(16), (2).toString(16)); // 2
// console.log("3: ADD 2,0,1: ", ADD(2, 0, 1).toString(16), (52 + 46).toString(16)); // 3
// console.log("4: SUB 3,0,1: ", SUB(3, 0, 1).toString(16), (52 - 46).toString(16)); // 4
// console.log("5: LSL 4,0,7: ", LSL(4, 0, 7).toString(16), (52 << 2).toString(16)); // 5
// console.log("6: OR 5,0,1: ", OR(5, 0, 1).toString(16), (52 | 46).toString(16)); // 6
// console.log("7: JMP 32: ", JMP(32).toString(16)); // 7
// console.log("32: OR 8,7,7: ", OR(8, 7, 7).toString(16), (2).toString(16)); // 32
// console.log("33: LDR 9,2: ", LDR(9, 2).toString(16), (2).toString(16)); // 33
// console.log("34: BEQ 8,9,1: ", BEQ(8, 9, 1).toString(16)); // 34
// console.log("36: CLR 8: ", CLR(8).toString(16)); // 35 + 1 = 36
// console.log("37: LDR 10,0: ", LDR(10,0).toString(16)); // 37
// console.log("38: BEQ 8,10,1: ", BEQ(8,10,1).toString(16)); // 38
// console.log("40: SW 0,7,0: ", SW(0, 7, 0).toString(16)); // 39 + 1 = 40
// console.log("41: LDR 10,0: ", LDR(10,0).toString(16)); // 37
// console.log("42: LW 11,7,0: ", LW(11, 7, 0).toString(16));
// console.log("43: SUB 12,11,0: ", SUB(12, 11, 0).toString(16));
// console.log("44: MUL 13,0,1: ", MUL(13, 0, 1).toString(16), (52 * 46).toString(16));
// console.log("45: DIV 14,0,1: ", DIV(14, 0, 1).toString(16), Math.floor(52 / 46).toString(16));
// console.log("46: MOD 15,0,1: ", MOD(15, 0, 1).toString(16), (52 % 46).toString(16));
// console.log("47: HLT: ", HLT().toString(16));
// ==================== 汇编编译器 ====================
const fs = require('fs');
// 解析寄存器编号 (R0-R31 或 r0-r31)
function parseRegister(reg) {
const match = reg.trim().match(/^r(\d+)$/i);
if (!match) {
throw new Error(`Invalid register format: ${reg}`);
}
const num = parseInt(match[1], 10);
if (num < 0 || num > 31) {
throw new Error(`Register out of range: ${reg} (must be R0-R31)`);
}
return num;
}
// 解析立即数(支持十进制和十六进制)
function parseImmediate(imm) {
const trimmed = imm.trim();
if (trimmed.startsWith('0x') || trimmed.startsWith('0X')) {
return parseInt(trimmed, 16);
}
return parseInt(trimmed, 10);
}
// 解析单行汇编代码
// 返回值: { type: 'instruction' | 'org', value: number }
function parseLine(line) {
// 去除注释(支持 // 和 ;)
let code = line.split('//')[0].split(';')[0].trim();
if (code === '') {
return null;
}
// 分割指令和参数
const parts = code.split(/\s+/);
const opcode = parts[0].toUpperCase();
// 处理 .org 伪指令
if (opcode === '.ORG') {
const argsStr = parts.slice(1).join('');
const args = argsStr.split(',').filter(arg => arg !== '');
if (args.length !== 1) throw new Error('.ORG requires 1 argument: address');
return { type: 'org', value: parseImmediate(args[0]) };
}
const argsStr = parts.slice(1).join('');
const args = argsStr.split(',').filter(arg => arg !== '');
let machineCode;
switch (opcode) {
case 'ADD':
if (args.length !== 3) throw new Error('ADD requires 3 arguments: Rd,Rs,Rt');
machineCode = ADD(parseRegister(args[0]), parseRegister(args[1]), parseRegister(args[2]));
break;
case 'SUB':
if (args.length !== 3) throw new Error('SUB requires 3 arguments: Rd,Rs,Rt');
machineCode = SUB(parseRegister(args[0]), parseRegister(args[1]), parseRegister(args[2]));
break;
case 'LSL':
if (args.length !== 3) throw new Error('LSL requires 3 arguments: Rd,Rs,Rt');
machineCode = LSL(parseRegister(args[0]), parseRegister(args[1]), parseRegister(args[2]));
break;
case 'OR':
if (args.length !== 3) throw new Error('OR requires 3 arguments: Rd,Rs,Rt');
machineCode = OR(parseRegister(args[0]), parseRegister(args[1]), parseRegister(args[2]));
break;
case 'MUL':
if (args.length !== 3) throw new Error('MUL requires 3 arguments: Rd,Rs,Rt');
machineCode = MUL(parseRegister(args[0]), parseRegister(args[1]), parseRegister(args[2]));
break;
case 'DIV':
if (args.length !== 3) throw new Error('DIV requires 3 arguments: Rd,Rs,Rt');
machineCode = DIV(parseRegister(args[0]), parseRegister(args[1]), parseRegister(args[2]));
break;
case 'MOD':
if (args.length !== 3) throw new Error('MOD requires 3 arguments: Rd,Rs,Rt');
machineCode = MOD(parseRegister(args[0]), parseRegister(args[1]), parseRegister(args[2]));
break;
case 'LW':
if (args.length !== 3) throw new Error('LW requires 3 arguments: Rd,Rs,imm16');
machineCode = LW(parseRegister(args[0]), parseRegister(args[1]), parseImmediate(args[2]));
break;
case 'SW':
if (args.length !== 3) throw new Error('SW requires 3 arguments: Rd,Rs,imm16');
machineCode = SW(parseRegister(args[0]), parseRegister(args[1]), parseImmediate(args[2]));
break;
case 'BEQ':
if (args.length !== 3) throw new Error('BEQ requires 3 arguments: Rs,Rt,imm16');
machineCode = BEQ(parseRegister(args[0]), parseRegister(args[1]), parseImmediate(args[2]));
break;
case 'JMP':
if (args.length !== 1) throw new Error('JMP requires 1 argument: imm26');
machineCode = JMP(parseImmediate(args[0]));
break;
case 'HLT':
if (args.length !== 0) throw new Error('HLT requires no arguments');
machineCode = HLT();
break;
case 'CLR':
if (args.length !== 1) throw new Error('CLR requires 1 argument: Rd');
machineCode = CLR(parseRegister(args[0]));
break;
case 'LDR':
if (args.length !== 2) throw new Error('LDR requires 2 arguments: Rd,imm21');
machineCode = LDR(parseRegister(args[0]), parseImmediate(args[1]));
break;
default:
throw new Error(`Unknown instruction: ${opcode}`);
}
return { type: 'instruction', value: machineCode >>> 0 }; // 转换为无符号32位整数
}
// 解析带标签引用的汇编行
// currentAddr 用于计算相对跳转偏移
function parseLineWithLabels(line, labels, currentAddr) {
// 去除注释(支持 // 和 ;)
let code = line.split('//')[0].split(';')[0].trim();
if (code === '' || code.endsWith(':')) {
return null;
}
// 跳过 .org
if (code.toUpperCase().startsWith('.ORG')) {
return null;
}
// 识别指令类型
const parts = code.split(/\s+/);
const opcode = parts[0].toUpperCase();
// 替换标签引用为实际值
for (const [labelName, labelAddr] of labels) {
const regex = new RegExp(`\\b${labelName}\\b`, 'g');
// 对于相对跳转指令 (BEQ),计算偏移量: offset = label - (currentAddr + 1)
if (opcode === 'BEQ' || opcode === 'BNE') {
const offset = labelAddr - (currentAddr + 1);
code = code.replace(regex, offset.toString());
} else {
// 对于绝对跳转 (JMP),使用标签地址
code = code.replace(regex, labelAddr.toString());
}
}
return parseLine(code);
}
// 从内存映射生成 MIF 文件内容(支持非连续地址)
function generateMifFromMemory(memory) {
const depth = 8192;
let content = [];
content.push('-- Copyright (C) 1991-2009 Altera Corporation');
content.push('-- Your use of Altera Corporation\'s design tools, logic functions');
content.push('-- and other software and tools, and its AMPP partner logic');
content.push('-- functions, and any output files from any of the foregoing');
content.push('-- (including device programming or simulation files), and any');
content.push('-- associated documentation or information are expressly subject');
content.push('-- to the terms and conditions of the Altera Program License');
content.push('-- Subscription Agreement, Altera MegaCore Function License');
content.push('-- Agreement, or other applicable license agreement, including,');
content.push('-- without limitation, that your use is for the sole purpose of');
content.push('-- programming logic devices manufactured by Altera and sold by');
content.push('-- Altera or its authorized distributors. Please refer to the');
content.push('-- applicable agreement for further details.');
content.push('');
content.push('-- Quartus II generated Memory Initialization File (.mif)');
content.push('');
content.push('WIDTH=32;');
content.push(`DEPTH=${depth};`);
content.push('');
content.push('ADDRESS_RADIX=UNS;');
content.push('DATA_RADIX=HEX;');
content.push('');
content.push('CONTENT BEGIN');
// 获取排序后的地址
const addresses = Array.from(memory.keys()).sort((a, b) => a - b);
if (addresses.length === 0) {
content.push(`\t[0..${depth - 1}]\t:\t00000000;`);
} else {
let lastAddr = -1;
for (const addr of addresses) {
// 填充当前地址和上一个地址之间的空白
if (addr > lastAddr + 1) {
const start = lastAddr + 1;
const end = addr - 1;
if (start === end) {
content.push(`\t${start}\t:\t00000000;`);
} else {
content.push(`\t[${start}..${end}]\t:\t00000000;`);
}
}
const hex = memory.get(addr).toString(16).toUpperCase().padStart(8, '0');
content.push(`\t${addr}\t:\t${hex};`);
lastAddr = addr;
}
// 填充剩余地址
if (lastAddr < depth - 1) {
content.push(`\t[${lastAddr + 1}..${depth - 1}]\t:\t00000000;`);
}
}
content.push('END;');
content.push('');
return content.join('\n');
}
// 第一遍扫描:收集标签地址
function collectLabels(lines) {
const labels = new Map();
let currentAddress = 0;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
// 去除注释
let code = line.split('//')[0].split(';')[0].trim();
if (code === '') continue;
// 检查是否是标签(以冒号结尾)
if (code.endsWith(':')) {
const labelName = code.slice(0, -1).trim();
labels.set(labelName, currentAddress);
continue;
}
// 跳过 .org,它只是设置地址
if (code.toUpperCase().startsWith('.ORG')) {
const argsStr = code.substring(4).trim();
currentAddress = parseImmediate(argsStr);
continue;
}
// 其他指令占用一个地址
currentAddress++;
}
return labels;
}
// 编译汇编文件
function compile(inputFile, outputFile) {
console.log(`\nCompiling ${inputFile}...`);
const asmContent = fs.readFileSync(inputFile, 'utf-8');
const lines = asmContent.split('\n');
// 第一遍:收集标签
const labels = collectLabels(lines);
// 第二遍:生成机器码
const memory = new Map();
let currentAddress = 0;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
try {
// 去除注释
let code = line.split('//')[0].split(';')[0].trim();
if (code === '') continue;
// 跳过标签行
if (code.endsWith(':')) continue;
// 处理 .org
if (code.toUpperCase().startsWith('.ORG')) {
const argsStr = code.substring(4).trim();
currentAddress = parseImmediate(argsStr);
continue;
}
// 解析指令,传入标签表用于解析标签引用
const result = parseLineWithLabels(line, labels, currentAddress);
if (result !== null && result.type === 'instruction') {
memory.set(currentAddress, result.value);
currentAddress++;
}
} catch (err) {
console.error(`Error on line ${i + 1}: ${line}`);
console.error(` ${err.message}`);
process.exit(1);
}
}
const mifContent = generateMifFromMemory(memory);
fs.writeFileSync(outputFile, mifContent);
console.log(`Successfully compiled to ${outputFile}`);
console.log(`Generated ${memory.size} instructions`);
if (labels.size > 0) {
console.log('Labels:');
for (const [name, addr] of labels) {
console.log(` ${name}: 0x${addr.toString(16)}`);
}
}
}
// CLI 入口
function main() {
const args = process.argv.slice(2);
if (args.length < 1) {
console.log('Usage: node compiler.js <input.asm> [output.mif]');
console.log('');
console.log('If output file is not specified, defaults to <input>.mif');
console.log('');
console.log('Supported instructions:');
console.log(' ADD Rd,Rs,Rt - Add');
console.log(' SUB Rd,Rs,Rt - Subtract');
console.log(' LSL Rd,Rs,Rt - Logical Shift Left');
console.log(' OR Rd,Rs,Rt - Bitwise OR');
console.log(' MUL Rd,Rs,Rt - Multiply');
console.log(' DIV Rd,Rs,Rt - Divide');
console.log(' MOD Rd,Rs,Rt - Modulo');
console.log(' LW Rd,Rs,imm - Load Word');
console.log(' SW Rd,Rs,imm - Store Word');
console.log(' BEQ Rs,Rt,imm - Branch if Equal');
console.log(' JMP imm - Jump');
console.log(' HLT - Halt');
console.log(' CLR Rd - Clear Register');
console.log(' LDR Rd,imm - Load Immediate');
console.log('');
console.log('Registers: R0-R31 (case insensitive)');
console.log('Immediate: decimal or hexadecimal (0x prefix)');
console.log('Comments: // or ;');
console.log('Directives:');
console.log(' .org addr - Set current address (for non-contiguous code)');
return;
}
const inputFile = args[0];
const outputFile = args[1] || inputFile.replace(/\.asm$/i, '.mif');
if (!fs.existsSync(inputFile)) {
console.error(`Error: Input file "${inputFile}" not found`);
process.exit(1);
}
compile(inputFile, outputFile);
}
// 仅在直接运行时执行 CLI(不是被 require 时)
if (require.main === module) {
main();
}
// 导出函数供其他模块使用
module.exports = {
ADD, SUB, LSL, OR, MUL, DIV, MOD,
LW, SW, BEQ, JMP, HLT, CLR, LDR,
parseLine, compile
};