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
|
#include <backend.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <assert.h>
#include "../sv.h"
static FILE *src;
static FILE *dst;
void die(const char *name, const char *file, size_t line, const char *fmt, ...)
{
printf("ERROR %s(%s:%d): ", name, file, line);
va_list args;
va_start(args, fmt);
vprintf(fmt, args);
va_end(args);
printf("\nCompilation failed!\n");
exit(1);
}
void debug(const char *name, const char *file, size_t line, const char *fmt, ...)
{
printf("LOG %s(%s:%d): ", name, file, line);
va_list args;
va_start(args, fmt);
vprintf(fmt, args);
va_end(args);
}
struct string_view backend_stream_init_src(const char *path)
{
assert(path != NULL);
src = fopen(path, "r");
fseek(src, 0, SEEK_END);
size_t size = ftell(src);
fseek(src, 0, SEEK_SET);
char *buf = malloc(size + 1);
if(fread(buf, size, 1, src) == 0)
DIE("Failed to read the file!\n");
buf[size] = '\0';
return (struct string_view){.buf = buf, .len = size};
}
void backend_stream_init_dst(const char *path)
{
dst = fopen(path, "w");
}
void backend_stream_close_src()
{
fclose(src);
}
void backend_stream_close_dst()
{
fclose(dst);
}
void emit8(uint8_t out)
{
fprintf(dst, "%02x", out);
}
void emit16(uint16_t out)
{
uint8_t test = 0;
for(int i = 0; i < 2; i++) {
test = (out >> (i * 8)) & 0xFF;
fprintf(dst, "%02x", test);
}
}
void emit32(uint32_t out)
{
uint8_t test = 0;
for(int i = 0; i < 4; i++) {
test = (out >> (i * 8)) & 0xFF;
fprintf(dst, "%02x", test);
}
}
void emit64(uint64_t out)
{
uint8_t test = 0;
for(int i = 0; i < 8; i++) {
test = (out >> (i * 8)) & 0xFF;
fprintf(dst, "%02x", test);
}
}
|