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
use crate::{
compiler::state::State,
core::Expr::{self, *},
core::Expressions,
immediate,
x86::{
self, Ins, Reference,
Register::{self, *},
ASM,
},
};
use std::convert::TryFrom;
pub fn eval(s: &State, data: &str) -> ASM {
address(s, &Expr::Str(data.into()), RAX)
}
pub fn inline(s: &State) -> ASM {
let mut asm = ASM(vec![]);
for (symbol, index) in &s.symbols {
asm += Ins::from("");
asm += Ins::from(".p2align 3");
asm += x86::label(&label(*index));
asm += Ins(format!(".quad {}", symbol.len()));
asm += Ins(format!(".ascii \"{}\"", symbol))
}
asm
}
fn address(s: &State, t: &Expr, to: Register) -> ASM {
match t {
Expr::Str(tag) => {
let index = s.symbols.get(tag).unwrap_or_else(|| {
panic!("String `{}` not found in symbol table", tag)
});
x86::lea(to, &label(*index), immediate::STR).into()
}
Expr::Identifier(i) => match s.get(&i) {
Some(i) => x86::mov(to.into(), i.clone()).into(),
None => panic!("Undefined variable {}", i),
},
_ => panic!("expected string; got {:?}", t),
}
}
fn label(index: usize) -> String {
format!("inc_str_{}", index)
}
#[allow(clippy::identity_op)]
pub fn make(_: &State, size: i64) -> ASM {
let len = i64::try_from(size).unwrap();
let size = ((len + 7) / 8) * 8;
x86::mov(Reference::from(RSI + 0), len.into())
+ x86::mov(RAX.into(), RSI.into())
+ x86::or(RAX.into(), immediate::STR.into())
+ x86::add(RSI.into(), size.into())
}
pub fn lift(s: &mut State, prog: &Expressions) {
for e in &prog.0 {
lift1(s, e);
}
}
fn lift1(s: &mut State, prog: &Expr) {
match prog {
Str(reference) => {
if !s.symbols.contains_key(reference) {
s.symbols.insert(reference.clone(), s.symbols.len());
}
}
Let { bindings, body } => {
for (_name, expr) in bindings {
lift1(s, expr);
}
for b in body {
lift1(s, b)
}
}
List(list) => {
for l in list {
lift1(s, l);
}
}
_ => {}
}
}