summaryrefslogtreecommitdiff
path: root/lib94/warrior.cpp
blob: 47c9b02043c4391d7912b3d1bfb8993a2cb9cca3 (plain) (blame)
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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
#include <lib94/lib94.hpp>
#include <functional>
#include <fstream>
#include <cctype>
#include <cstdio>
#include <memory>
#include <map>

namespace lib94 {

  static const std::string opcode_strings[] = {
    "dat", "mov", "add", "sub", "mul", "div", "mod", "jmp",
    "jmz", "jmn", "djn", "seq", "sne", "slt", "spl", "nop"
  };

  static const std::string modifier_strings[] = {
    "a", "b", "ab", "ba", "f", "x", "i"
  };

  static const char mode_chars[] = "#$*@{<}>";

  std::string instruction_to_string(const instruction &instr) {
    return
      opcode_strings[instr.op] + '.' + modifier_strings[instr.mod] + ' ' +
      mode_chars[instr.amode] + std::to_string(instr.anumber) + ", " +
      mode_chars[instr.bmode] + std::to_string(instr.bnumber);
  }

  number_t real_mod(number_t input) {
    return (input % LIB94_CORE_SIZE + LIB94_CORE_SIZE) % LIB94_CORE_SIZE;
  }

  struct number_expr {
    virtual std::optional<number_t> to_number(const std::map<std::string, number_t> &label_offsets, const std::map<std::string, number_t> &macro_values, number_t this_offset) = 0;
  };

  struct label_number_expr : public number_expr {
    std::string label;

    virtual std::optional<number_t> to_number(const std::map<std::string, number_t> &label_offsets, const std::map<std::string, number_t> &macro_values, number_t this_offset) {
      auto result = label_offsets.find(label);
      if (result != label_offsets.end())
        return real_mod(result->second - this_offset);
      result = macro_values.find(label);
      if (result != macro_values.end())
        return result->second;
      return {};
    }
  };

  struct number_number_expr : public number_expr {
    number_t value;

    virtual std::optional<number_t> to_number(const std::map<std::string, number_t> &, const std::map<std::string, number_t> &, number_t) {
      return real_mod(value);
    }
  };

  struct op_number_expr : public number_expr {
    std::unique_ptr<number_expr> left;
    std::unique_ptr<number_expr> right;
    std::function<std::optional<number_t> (number_t, number_t)> op;

    virtual std::optional<number_t> to_number(const std::map<std::string, number_t> &label_offsets, const std::map<std::string, number_t> &macro_values, number_t this_offset) {
      std::optional<number_t> left_result = left->to_number(label_offsets, macro_values, this_offset);
      std::optional<number_t> right_result = right->to_number(label_offsets, macro_values, this_offset);
      if (left_result.has_value() && right_result.has_value()) {
        std::optional<number_t> op_result = op(left_result.value(), right_result.value());
        if (op_result.has_value())
          return real_mod(op_result.value());
      }
      return {};
    }
  };

  struct negative_number_expr : public number_expr {
    std::unique_ptr<number_expr> inner;

    virtual std::optional<number_t> to_number(const std::map<std::string, number_t> &label_offsets, const std::map<std::string, number_t> &macro_values, number_t this_offset) {
      std::optional<number_t> inner_result = inner->to_number(label_offsets, macro_values, this_offset);
      if (inner_result.has_value())
        return LIB94_CORE_SIZE - inner_result.value();
      return {};
    }
  };

  bool valid_label(std::string candidate) {
    if (candidate == "")
      return false;

    if (!isalpha(candidate[0]) && candidate[0] != '_')
      return false;

    for (char ch : candidate)
      if (!isalnum(ch) && ch != '_')
        return false;

    return true;
  }

  size_t find_respecting_parentheses(std::string part, std::string candidates) {
    size_t layers = 0;

    for (int i = part.size() - 1; i >= 0; --i)
      if (layers == 0 && candidates.find(part[i]) != std::string::npos) {

        if (part[i] == '-' || part[i] == '+') {
          for (int j = i - 1; j >= 0; --j) {
            if (isalnum(part[j]) || part[j] == '_' || part[j] == ')')
              return i;
            if (part[j] != ' ')
              break;
          }
          continue;
        }

        return i;
      }

      else if (part[i] == ')')
        ++layers;
      else if (part[i] == '(')
        --layers;

    return std::string::npos;
  }

  std::optional<std::unique_ptr<number_expr>> to_number_expr(std::string part);

  std::optional<std::unique_ptr<number_expr>> make_op_expr(std::string part, size_t split) {
    std::string left = part.substr(0, split);
    std::string right = part.substr(split + 1);

    std::optional<std::unique_ptr<number_expr>> left_expr = to_number_expr(left);
    std::optional<std::unique_ptr<number_expr>> right_expr = to_number_expr(right);
    if (!left_expr.has_value() || !right_expr.has_value())
      return {};

    auto expr = std::make_unique<op_number_expr>();
    expr->left = std::move(left_expr.value());
    expr->right = std::move(right_expr.value());

    switch (part[split]) {
      case '+': expr->op = [](number_t a, number_t b) {return a + b;}; break;
      case '-': expr->op = [](number_t a, number_t b) {return a - b;}; break;
      case '*': expr->op = [](number_t a, number_t b) {return a * b;}; break;
      case '/': expr->op = [](number_t a, number_t b) -> std::optional<number_t> {
        if (b == 0)
          return {};
        return a / b;
        }; break;
      case '%': expr->op = [](number_t a, number_t b) -> std::optional<number_t> {
        if (b == 0)
          return {};
        return a % b;
        }; break;
    }

    return expr;
  }

  std::string trim_spaces(std::string str) {
    size_t start = str.find_first_not_of(' ');
    size_t end = str.find_last_not_of(' ') + 1;
    if (start == std::string::npos)
      return "";
    return str.substr(start, end - start);
  }

  std::optional<std::unique_ptr<number_expr>> to_number_expr(std::string part) {
    part = trim_spaces(part);
    if (part == "")
      return {};

    size_t split = find_respecting_parentheses(part, "+-");
    if (split == std::string::npos)
      split = find_respecting_parentheses(part, "*/%");
    if (split != std::string::npos)
      return make_op_expr(part, split);

    if (part[0] == '(' && part[part.size() - 1] == ')')
      return to_number_expr(part.substr(1, part.size() - 2));

    if (part[0] == '+')
      return to_number_expr(part.substr(1));

    if (part[0] == '-') {
      std::optional<std::unique_ptr<number_expr>> inner = to_number_expr(part.substr(1));
      if (!inner.has_value())
        return {};
      std::unique_ptr<negative_number_expr> expr = std::make_unique<negative_number_expr>();
      expr->inner = std::move(inner.value());
      return expr;
    }

    try {
      size_t count;
      number_t number = std::stoul(part, &count);
      if (count == part.size()) {
        std::unique_ptr<number_number_expr> expr = std::make_unique<number_number_expr>();
        expr->value = number;
        return expr;
      }
    }
    catch (const std::exception &e) {}

    if (valid_label(part)) {
      std::unique_ptr<label_number_expr> expr = std::make_unique<label_number_expr>();
      expr->label = part;
      return expr;
    }

    return {};
  }

  //using unqiue_ptr to refer to this in case i add more types in the future
  struct assert_expr {
    std::unique_ptr<number_expr> left;
    std::unique_ptr<number_expr> right;
    std::function<bool (number_t, number_t)> comparison;

    std::optional<bool> is_true(const std::map<std::string, number_t> &label_offsets, const std::map<std::string, number_t> &macro_values, number_t this_offset) {
      auto left_result = left->to_number(label_offsets, macro_values, this_offset);
      auto right_result = right->to_number(label_offsets, macro_values, this_offset);
      if (left_result.has_value() && right_result.has_value())
        return comparison(left_result.value(), right_result.value());
      return {};
    }
  };

  std::optional<std::unique_ptr<assert_expr>> make_assert_expr(std::string part, std::string sep, std::function<bool (number_t, number_t)> comparison) {
    size_t pos = part.find(sep);
    if (pos == std::string::npos)
      return {};

    auto left = to_number_expr(part.substr(0, pos));
    auto right = to_number_expr(part.substr(pos + sep.size()));

    if (!left.has_value() || !right.has_value())
      return {};

    return std::make_unique<assert_expr>((assert_expr){
      .left = std::move(left.value()), .right = std::move(right.value()), .comparison = comparison
    });
  }

  std::optional<std::unique_ptr<assert_expr>> to_assert_expr(std::string part) {
    std::optional<std::unique_ptr<assert_expr>> result;

    result = make_assert_expr(part, "==", [](number_t a, number_t b) {return a == b;});
    if (result)
      return result;

    result = make_assert_expr(part, "<=", [](number_t a, number_t b) {return a <= b;});
    if (result)
      return result;

    result = make_assert_expr(part, ">=", [](number_t a, number_t b) {return a >= b;});
    if (result)
      return result;

    result = make_assert_expr(part, "!=", [](number_t a, number_t b) {return a != b;});
    if (result)
      return result;

    result = make_assert_expr(part, "<", [](number_t a, number_t b) {return a < b;});
    if (result)
      return result;

    return make_assert_expr(part, ">", [](number_t a, number_t b) {return a > b;});
  }

  static const std::map<char, mode> mode_symbols = {
    {'#', IMMEDIATE},   {'$', DIRECT},
    {'*', A_INDIRECT},  {'@', B_INDIRECT},
    {'{', A_DECREMENT}, {'<', B_DECREMENT},
    {'}', A_INCREMENT}, {'>', B_INCREMENT}
  };

  std::optional<std::pair<mode, std::unique_ptr<number_expr>>> to_field(std::string part) {
    if (part == "")
      return {};

    mode m = DIRECT;

    auto result = mode_symbols.find(part[0]);
    if (result != mode_symbols.end()) {
      m = result->second;
      part = trim_spaces(part.substr(1));
    }

    std::optional<std::unique_ptr<number_expr>> expr = to_number_expr(part);
    if (expr.has_value())
      return std::make_pair<>(m, std::move(expr.value()));

    return {};
  }

  static const std::map<std::string, opcode> opcode_names = {
    {"dat", DAT}, {"mov", MOV}, {"add", ADD}, {"sub", SUB},
    {"mul", MUL}, {"div", DIV}, {"mod", MOD}, {"jmp", JMP},
    {"jmz", JMZ}, {"jmn", JMN}, {"djn", DJN}, {"seq", SEQ},
    {"sne", SNE}, {"slt", SLT}, {"spl", SPL}, {"nop", NOP},
    {"cmp", SEQ}, {"jnz", JMN}
  };

  struct future_instruction {
    size_t source_line;
    opcode op;
    modifier mod;
    mode amode;
    mode bmode;
    std::unique_ptr<number_expr> anumber;
    std::unique_ptr<number_expr> bnumber;
  };

  struct macro_definition {
    size_t source_line;
    std::unique_ptr<number_expr> definition;
    number_t offset;
  };

  struct assertion {
    size_t source_line;
    std::unique_ptr<assert_expr> expr;
    number_t offset;
  };

  std::variant<warrior *, std::string> compile_warrior(std::string source) {
    for (char &ch : source)
      if (ch == '\t' || ch == '\r')
        ch = ' ';

    std::unique_ptr<warrior> w = std::make_unique<warrior>();

    std::vector<future_instruction> instructions;
    std::map<std::string, number_t> label_offsets;
    std::map<std::string, macro_definition> macro_definitions;
    std::vector<assertion> assertions;
    std::optional<std::unique_ptr<number_expr>> org = {};
    number_t org_offset = -1;
    size_t org_source_line = -1;

    size_t on_line = 0;

    while (true) {
      if (source == "")
        break;

      ++on_line;

      size_t newline = source.find('\n');
      if (newline == std::string::npos)
        newline = source.size();

      std::string line = source.substr(0, newline);
      source = source.substr(newline + 1);

      size_t semicolon = line.find(';');

      if (semicolon != std::string::npos) {
        std::string comment = trim_spaces(line.substr(semicolon + 1));
        line = line.substr(0, semicolon);

        if (comment.starts_with("name "))
          w->name = trim_spaces(comment.substr(5));
        else if (comment.starts_with("author "))
          w->author = trim_spaces(comment.substr(7));

        else if (comment.starts_with("assert ")) {
          auto expr = to_assert_expr(comment.substr(7));
          if (expr.has_value())
            assertions.emplace_back((assertion){
              .source_line = on_line,
              .expr = std::move(expr.value()),
              .offset = (number_t)instructions.size()
            });
          else
            return std::string("bad expression on line ") + std::to_string(on_line);
        }
      }

      for (char &ch : line)
        ch = tolower(ch);

    return_after_label:
      line = trim_spaces(line);
      if (line == "")
        continue;

      size_t equ = line.find(" equ ");
      if (equ != std::string::npos) {

        std::string macro_name = trim_spaces(line.substr(0, equ).substr());

        if (!valid_label(macro_name))
          return std::string("bad label on line ") + std::to_string(on_line);
        if (macro_definitions.contains(macro_name) || label_offsets.contains(macro_name))
          return std::string("duplicate label on line ") + std::to_string(on_line);

        auto macro_def = to_number_expr(line.substr(equ + 5));
        if (!macro_def.has_value())
          return std::string("bad expression on line ") + std::to_string(on_line);

        macro_definitions.emplace(macro_name,
          (macro_definition){
            .source_line = on_line,
            .definition = std::move(macro_def.value()),
            .offset = (number_t)instructions.size()
          }
        );

        continue;

      }

      future_instruction instr;
      instr.source_line = on_line;

      size_t sep = line.find_first_of(" .");
      if (sep == std::string::npos)
        sep = line.size();

      std::string opcode_str = trim_spaces(line.substr(0, sep));
      line = trim_spaces(line.substr(sep));

      if (opcode_str == "org" || opcode_str == "end") {
        if (org.has_value())
          return std::string("duplicate org on line ") + std::to_string(on_line);

        org = to_number_expr(line);

        if (!org.has_value())
          return std::string("bad expression on line ") + std::to_string(on_line);

        org_offset = instructions.size();
        org_source_line = on_line;
        continue;
      }

      auto opcode_it = opcode_names.find(opcode_str);

      if (opcode_it == opcode_names.end()) {
        if (!valid_label(opcode_str))
          return std::string("bad label or unknown opcode on line ") + std::to_string(on_line);

        if (label_offsets.contains(opcode_str) || macro_definitions.contains(opcode_str))
          return std::string("duplicate label on line ") + std::to_string(on_line);

        label_offsets[opcode_str] = (number_t)instructions.size();

        goto return_after_label;
      }

      instr.op = opcode_it->second;

      bool got_mod = false;

      if (line != "" && line[0] == '.') {
        line = trim_spaces(line.substr(1));

        if (line == "")
          return std::string("dot with no modifier on line ") + std::to_string(on_line);

        got_mod = true;

        size_t mod_length = 2;

        if (line.starts_with("ab"))
          instr.mod = AB;
        else if (line.starts_with("ba"))
          instr.mod = BA;
        else {

          mod_length = 1;

          if (line[0] == 'a')
            instr.mod = A;
          else if (line[0] == 'b')
            instr.mod = B;
          else if (line[0] == 'f')
            instr.mod = F;
          else if (line[0] == 'x')
            instr.mod = X;
          else if (line[0] == 'i')
            instr.mod = I;

          else
            return std::string("unknown opcode modifier on line ") + std::to_string(on_line);

        }

        line = trim_spaces(line.substr(mod_length));
      }

      std::optional<std::pair<mode, std::unique_ptr<number_expr>>> afield, bfield;

      if (line == "") {
        afield = to_field("0");
        bfield = to_field("0");
      }

      else {
        size_t comma = line.find(",");

        if (comma == std::string::npos) {
          afield = to_field(line);
          bfield = to_field("0");
        }

        else {
          std::string apart = trim_spaces(line.substr(0, comma));
          std::string bpart = trim_spaces(line.substr(comma + 1));
          afield = to_field(apart);
          bfield = to_field(bpart);
        }
      }

      if (!afield.has_value() || !bfield.has_value())
        return std::string("bad expression on line ") + std::to_string(on_line);

      instr.amode = afield.value().first;
      instr.bmode = bfield.value().first;
      instr.anumber = std::move(afield.value().second);
      instr.bnumber = std::move(bfield.value().second);

      if (!got_mod)
        switch (instr.op) {

          case DAT:
            instr.mod = F;
            break;

          case MOV:
          case SEQ:
          case SNE:
            if (instr.amode == IMMEDIATE)
              instr.mod = AB;
            else if (instr.bmode == IMMEDIATE)
              instr.mod = B;
            else
              instr.mod = I;
            break;

          case ADD:
          case SUB:
          case MUL:
          case DIV:
          case MOD:
            if (instr.amode == IMMEDIATE)
              instr.mod = AB;
            else if (instr.bmode == IMMEDIATE)
              instr.mod = B;
            else
              instr.mod = F;
            break;

          case SLT:
            if (instr.amode == IMMEDIATE)
              instr.mod = AB;
            instr.mod = B;
            break;

          case JMP:
          case JMZ:
          case JMN:
          case DJN:
          case SPL:
          case NOP:
            instr.mod = B;
            break;

        }

      instructions.push_back(std::move(instr));
    }

    if (w->name == "")
      return "no name";
    if (w->author == "")
      return "no author";

    std::map<std::string, number_t> macro_values;
    for (const auto &macro : macro_definitions) {
      auto result = macro.second.definition->to_number(label_offsets, macro_values, macro.second.offset);
      if (result.has_value())
        macro_values[macro.first] = result.value();
      else
        return std::string("bad expression on line ") + std::to_string(macro.second.source_line);
    }

    for (const auto &a : assertions) {
      auto result = a.expr->is_true(label_offsets, macro_values, a.offset);
      if (!result.has_value())
        return std::string("bad expression on line ") + std::to_string(a.source_line);
      if (!result.value())
        return std::string("failed assertion on line ") + std::to_string(a.source_line);
    }

    if (org.has_value()) {
      std::optional<number_t> org_number = org.value()->to_number(label_offsets, macro_values, org_offset);
      if (org_number.has_value())
        w->org = real_mod(org_number.value() + org_offset);
      else
        return std::string("bad expression on line ") + std::to_string(org_source_line);
    }

    for (size_t i = 0; i < instructions.size(); ++i) {
      const future_instruction &instr = instructions[i];
      std::optional<number_t> anumber = instr.anumber->to_number(label_offsets, macro_values, i);
      std::optional<number_t> bnumber = instr.bnumber->to_number(label_offsets, macro_values, i);
      if (!anumber.has_value() || !bnumber.has_value())
        return std::string("bad expression on line ") + std::to_string(instr.source_line);
      w->instructions.push_back({
        .op = instr.op, .mod = instr.mod, .amode = instr.amode, .bmode = instr.bmode,
        .anumber = anumber.value(), .bnumber = bnumber.value()
      });
    }

    return w.release();
  }

  struct wheader {
    size_t name_size;
    size_t author_size;
    size_t instructions_size;
    number_t org;
  };

  bool save_warrior(const warrior &w, const std::filesystem::path &to) {
    FILE *f = fopen(to.c_str(), "wb");
    if (!f)
      return false;

    wheader wh = {
      .name_size = w.name.size(), .author_size = w.author.size(),
      .instructions_size = w.instructions.size(), .org = w.org
    };

    fwrite(&wh, sizeof(wheader), 1, f);
    fwrite(w.name.c_str(), w.name.size(), 1, f);
    fwrite(w.author.c_str(), w.author.size(), 1, f);
    fwrite(w.instructions.data(), sizeof(instruction) * w.instructions.size(), 1, f);

    fclose(f);
    return true;
  }

  std::optional<warrior *> load_warrior(const std::filesystem::path &from) {
    FILE *f = fopen(from.c_str(), "rb");
    if (!f)
      return {};

    std::unique_ptr<warrior> w = std::make_unique<warrior>();

    wheader wh;
    fread(&wh, sizeof(wheader), 1, f);

    w->name.resize(wh.name_size);
    w->author.resize(wh.author_size);
    w->instructions.resize(wh.instructions_size);
    w->org = wh.org;

    fread(w->name.data(), wh.name_size, 1, f);
    fread(w->author.data(), wh.author_size, 1, f);
    fread(w->instructions.data(), wh.instructions_size, 1, f);

    fclose(f);

    for (const instruction &i : w->instructions)
      if (i.op > NOP || i.mod > I || i.amode > B_INCREMENT || i.bmode > B_INCREMENT ||
          i.anumber >= LIB94_CORE_SIZE || i.bnumber >= LIB94_CORE_SIZE)
        return {};

    return w.release();
  }

}