forked from nulang-org/nulang
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathemitter.nula
More file actions
69 lines (62 loc) · 2.14 KB
/
Copy pathemitter.nula
File metadata and controls
69 lines (62 loc) · 2.14 KB
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
// bootstrap/emitter.nula — Stage 1: JSON emitter for .nbc generation
//
// Programs: 0=42, 1=add, 2=if, 3=double, 4=fact
// Change `prog` to select. All bytecodes verified via integration tests.
fn emit_json(name: String, instrs: String, consts: String) {
perform IO.print("{")
perform IO.print("\"name\":\"")
perform IO.print(name)
perform IO.print("\",")
perform IO.print("\"instructions\":[")
perform IO.print(instrs)
perform IO.print("],")
perform IO.print("\"constants\":[")
perform IO.print(consts)
perform IO.print("]")
perform IO.print("}")
}
fn emit_42() {
emit_json("lit42",
"\"07000000\",\"57000000\"",
"{\"type\":\"Int\",\"value\":42}")
}
fn emit_add() {
emit_json("add",
"\"07000000\",\"07000101\",\"20000100\",\"57000000\"",
"{\"type\":\"Int\",\"value\":1},{\"type\":\"Int\",\"value\":2}")
}
fn emit_if() {
emit_json("if_test",
"\"07000000\",\"07000101\",\"41000102\",\"52020004\"," +
"\"07000200\",\"50000300\",\"07000300\",\"57000000\"",
"{\"type\":\"Int\",\"value\":1},{\"type\":\"Int\",\"value\":2}," +
"{\"type\":\"Int\",\"value\":10},{\"type\":\"Int\",\"value\":20}")
}
fn emit_double() {
// fn double(x) { x*2 }; main() { double(21) }
emit_json("double21",
"\"07000001\",\"22000100\",\"57000000\"," +
"\"07000100\",\"03010000\",\"54010100\",\"57000000\"",
"{\"type\":\"Int\",\"value\":2},{\"type\":\"Int\",\"value\":21}")
}
fn emit_fact() {
// fn fact(n) { if n<=1 then 1 else n*fact(n-1) }; main() { fact(6) }
emit_json("fact6",
"\"04010000\",\"43000102\",\"52020003\"," +
"\"04000000\",\"57000000\"," +
"\"12000300\",\"21000100\",\"03040000\"," +
"\"54040100\",\"22030000\",\"57000000\"," +
"\"07000000\",\"03010000\",\"54010100\",\"57000000\"",
"{\"type\":\"Int\",\"value\":6}")
}
fn main() {
let prog = 4 in // 0=42, 1=add, 2=if, 3=double, 4=fact
match prog {
case 0 => emit_42()
case 1 => emit_add()
case 2 => emit_if()
case 3 => emit_double()
case 4 => emit_fact()
case _ => emit_42()
}
}