https://github.com/akkartik/mu/blob/master/subx/040---tests.cc
1
2
3
4
5
6
7
8
9
10
11
12 :(after "Begin Transforms")
13
14 Transform.push_back(create_test_function);
15
16
17 :(code)
18 void test_run_test() {
19 Reg[ESP].u = 0x100;
20 run(
21 "== 0x1\n"
22 "main:\n"
23 " e8/call run-tests/disp32\n"
24 " f4/halt\n"
25 "test-foo:\n"
26 " 01 d8\n"
27 " c3/return\n"
28 );
29
30 CHECK_TRACE_CONTENTS(
31 "run: 0x00000007 opcode: 01\n"
32 );
33 }
34
35 void create_test_function(program& p) {
36 if (p.segments.empty()) return;
37 segment& code = p.segments.at(0);
38 trace(3, "transform") << "-- create 'run-tests'" << end();
39 vector<line> new_insts;
40 for (int i = 0; i < SIZE(code.lines); ++i) {
41 line& inst = code.lines.at(i);
42 for (int j = 0; j < SIZE(inst.words); ++j) {
43 const word& curr = inst.words.at(j);
44 if (*curr.data.rbegin() != ':') continue;
45 if (!starts_with(curr.data, "test-")) continue;
46 string fn = drop_last(curr.data);
47 new_insts.push_back(call(fn));
48 }
49 }
50 if (new_insts.empty()) return;
51 code.lines.push_back(label("run-tests"));
52 code.lines.insert(code.lines.end(), new_insts.begin(), new_insts.end());
53 code.lines.push_back(ret());
54 }
55
56 string to_string(const segment& s) {
57 ostringstream out;
58 for (int i = 0; i < SIZE(s.lines); ++i) {
59 const line& l = s.lines.at(i);
60 for (int j = 0; j < SIZE(l.words); ++j) {
61 if (j > 0) out << ' ';
62 out << to_string(l.words.at(j));
63 }
64 out << '\n';
65 }
66 return out.str();
67 }
68
69 line call(string s) {
70 line result;
71 result.words.push_back(call());
72 result.words.push_back(disp32(s));
73 return result;
74 }
75
76 word call() {
77 word result;
78 result.data = "e8";
79 result.metadata.push_back("call");
80 return result;
81 }
82
83 word disp32(string s) {
84 word result;
85 result.data = s;
86 result.metadata.push_back("disp32");
87 return result;
88 }
89
90 line ret() {
91 line result;
92 result.words.push_back(word());
93 result.words.back().data = "c3";
94 result.words.back().metadata.push_back("return");
95 return result;
96 }