aboutsummaryrefslogtreecommitdiff
path: root/src/targets/bblc.c
diff options
context:
space:
mode:
authorMarvin Borner2024-01-17 01:25:18 +0100
committerMarvin Borner2024-01-17 01:25:18 +0100
commite790db8d6e39a6911606d21561a451701b8b3e29 (patch)
treee1fb07202e2e5980bad6c56551d20e1c6735cec8 /src/targets/bblc.c
parentb754e71ca502a5027ea3479eb3ea1a0ac28e5282 (diff)
Start shared abstraction target
Diffstat (limited to 'src/targets/bblc.c')
-rw-r--r--src/targets/bblc.c71
1 files changed, 71 insertions, 0 deletions
diff --git a/src/targets/bblc.c b/src/targets/bblc.c
new file mode 100644
index 0000000..555d400
--- /dev/null
+++ b/src/targets/bblc.c
@@ -0,0 +1,71 @@
+// Copyright (c) 2024, Marvin Borner <dev@marvinborner.de>
+// SPDX-License-Identifier: MIT
+
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+
+#include <target.h>
+#include <parse.h>
+#include <log.h>
+
+static void write_bit(char val, FILE *file, char *byte, int *bit)
+{
+ if (*bit > 7) { // flush byte
+ fwrite(byte, 1, 1, file);
+ *byte = 0;
+ *bit = 0;
+ }
+
+ // TODO: which endianness should be default?
+ if (val)
+ *byte |= 1UL << *bit;
+ /* *byte |= 1UL << (7 - *bit); */
+ (*bit)++;
+}
+
+static void fprint_bblc(struct term *term, struct bloc_parsed *bloc, FILE *file,
+ char *byte, int *bit)
+{
+ switch (term->type) {
+ case ABS:
+ write_bit(0, file, byte, bit);
+ write_bit(0, file, byte, bit);
+ fprint_bblc(term->u.abs.term, bloc, file, byte, bit);
+ break;
+ case APP:
+ write_bit(0, file, byte, bit);
+ write_bit(1, file, byte, bit);
+ fprint_bblc(term->u.app.lhs, bloc, file, byte, bit);
+ fprint_bblc(term->u.app.rhs, bloc, file, byte, bit);
+ break;
+ case VAR:
+ for (int i = 0; i <= term->u.var.index; i++)
+ write_bit(1, file, byte, bit);
+ write_bit(0, file, byte, bit);
+ break;
+ case REF:
+ if (term->u.ref.index + 1 >= bloc->length)
+ fatal("invalid ref index %ld\n", term->u.ref.index);
+ fprint_bblc(bloc->entries[bloc->length - term->u.ref.index - 2],
+ bloc, file, byte, bit);
+ break;
+ default:
+ fatal("invalid type %d\n", term->type);
+ }
+}
+
+static void write_bblc(struct bloc_parsed *bloc, FILE *file)
+{
+ char byte = 0;
+ int bit = 0;
+ fprint_bblc(bloc->entries[bloc->length - 1], bloc, file, &byte, &bit);
+
+ if (bit)
+ fwrite(&byte, 1, 1, file);
+}
+
+struct target_spec target_bblc = {
+ .name = "bblc",
+ .exec = write_bblc,
+};