compiler, vm - Corrected ASCII, UNICODE format issues
[hwframework.git] / hwc.c
bloba1e6586b06105a6f4f4a30104b040c71eb0db312
1 /* Hello world program compiler */
2 #include <ctype.h>
3 #include <stdarg.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
8 #include "vm.h"
10 static int parse(FILE *, FILE *);
11 static void write_hw_header(FILE *, int);
12 static HwInstruction *get_instr(int);
13 static void compiler_error(const char *, ...);
15 int
16 main(int argc, char *argv[])
18 FILE *in, *out;
19 int in_count;
20 char *file_name = NULL;
21 if (argc == 1)
22 compiler_error("No input files!\n");
24 file_name = argv[1];
25 in = fopen(file_name, "rt");
26 if (in == NULL)
27 compiler_error("Cannot open file %s\n", file_name);
29 file_name[strlen(file_name)-1] = 'x';
30 out = fopen(file_name, "wb");
31 if (out == NULL)
32 compiler_error("Cannot open file %s\n", file_name);
34 fseek(out, sizeof(HwHeader), SEEK_SET);
35 in_count = parse(in, out);
36 write_hw_header(out, in_count);
38 fclose(in);
39 fclose(out);
40 return 0;
43 static int
44 parse(FILE *in, FILE *out)
46 int input;
47 int i, count = 0;
48 int is_comment = 0;
49 HwInstruction *inst = NULL;
51 while (!feof(in)) {
52 fscanf(in, "%c", (char *)&input);
54 switch (input) {
55 case '#' :
56 is_comment = 1;
57 continue;
59 case '\n' :
60 is_comment = 0;
61 continue;
64 if (is_comment)
65 continue;
67 if (!isalpha(input))
68 continue;
70 inst = get_instr(input);
71 if (inst == NULL)
72 continue;
74 fwrite((void *)&inst->i_opcode, sizeof(uint8_t), 1, out);
75 count++;
77 return count;
80 static void
81 write_hw_header(FILE *out, int count)
83 HwHeader head = {
84 .hw_magic = HW_HEADER_MAGIC,
85 .hw_version = HW_HEADER_VERSION,
86 .hw_instr_count = count
89 fseek(out, 0L, SEEK_SET);
90 fwrite(&head, sizeof(HwHeader), 1, out);
93 static HwInstruction *
94 get_instr(int inst)
96 int i;
97 HwInstruction *hi = NULL;
98 for (i = 0; i < LAST_INSTRUCTION; i++) {
99 if (instructions[i].i_char == inst) {
100 hi = &instructions[i];
101 return hi;
104 return NULL;
107 static void
108 compiler_error(const char *fmt, ...)
110 va_list ap;
111 va_start(ap, fmt);
112 fprintf(stderr, "HW Compiler - (C) Akos Kovacs\n\nError: ");
113 vfprintf(stderr, fmt, ap);
114 va_end(ap);
115 exit(1);