1 /**
2  * Application interface for assembler command-line tool.
3  *
4  * Copyright © 2016, Eric Scrivner
5  *
6  * License: Subject to the terms of the MIT license, as written in the included
7  * LICENSE.txt file.
8  * Authors: Eric Scrivner
9  */
10 module phlogiston.cli.assembler;
11 
12 import std.file;
13 import std.stdio;
14 
15 import phlogiston.assembler.assembler;
16 
17 /// Interface for the assembler app.
18 class AssemblerApp {
19     /**
20      * This routine executes the assembler application.
21      *
22      * Params:
23      *     inputFile = The file to read assembly language code from.
24      *     outputFile = The file to write the bytecode string into.
25      */
26     public void execute(string inputFile, string outputFile) {
27         string assemblyCode = readText(inputFile);
28         Assembler assembler = new Assembler;
29 
30         try {
31             ubyte[] bytecode = assembler.assemble(assemblyCode);
32             writeBytecodeToFile(bytecode, outputFile);
33         } catch(AssemblerError ae) {
34             writeln("error: ", ae.msg);
35             return;
36         }
37     }
38 
39     /**
40      * This routine writes the given series of bytes to the given output file.
41      *
42      * Params:
43      *     bytecode = The bytecode to be written.
44      *     outputFile = The file to write the bytecode into.
45      */
46     private void writeBytecodeToFile(ref ubyte[] bytecode, string outputFile) {
47         File file = File(outputFile, "w");
48         foreach (val; bytecode) {
49             file.writef("%02x", val);
50         }
51     
52         file.write('\n');
53         file.close();
54     }
55 }