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
use std::sync::Arc;

use anyhow::Result;
use enum_as_inner::EnumAsInner;
use parking_lot::RwLock;

use crate::classfile::Addressed;
use crate::classfile::Resolvable;

#[derive(Debug, Clone)]
pub struct ConstantPool {
    // Needs to be shared because `Addressed` takes it
    // Might refactor this such that `Addressed` takes the pool when it tries to resolve
    entries: Arc<RwLock<Vec<ConstantEntry>>>,
}

impl Default for ConstantPool {
    fn default() -> Self {
        Self::new()
    }
}

impl ConstantPool {
    pub fn new() -> Self {
        Self {
            entries: Arc::new(RwLock::new(vec![])),
        }
    }

    pub fn insert(&mut self, entry: ConstantEntry) {
        let mut pool = self.entries.write();
        pool.push(entry)
    }

    pub fn get(&self, index: u16) -> Option<ConstantEntry> {
        let pool = self.entries.read();
        pool.get(index as usize).cloned()
    }

    pub fn address<T>(&self, for_index: u16) -> Addressed<T> {
        Addressed::from(for_index, Arc::clone(&self.entries))
    }

    pub(crate) fn perform_format_checking(&self) -> Result<()> {
        let entries = self.entries.read();
        for item in entries.iter() {
            match item {
                ConstantEntry::Class(data) => {
                    data.name.try_resolve()?;
                }
                ConstantEntry::Field(data) => {
                    data.class.try_resolve()?;
                    data.name_and_type.try_resolve()?;
                }
                ConstantEntry::Method(data) => {
                    data.class.try_resolve()?;
                    data.name_and_type.try_resolve()?;
                }
                ConstantEntry::InterfaceMethod(data) => {
                    data.class.try_resolve()?;
                    data.name_and_type.try_resolve()?;
                }
                ConstantEntry::String(data) => {
                    data.string.try_resolve()?;
                }
                ConstantEntry::Integer(_) => {}
                ConstantEntry::Float(_) => {}
                ConstantEntry::Long(_) => {}
                ConstantEntry::Double(_) => {}
                ConstantEntry::NameAndType(data) => {
                    data.name.try_resolve()?;
                    data.descriptor.try_resolve()?;
                }
                ConstantEntry::Utf8(_) => {}
                ConstantEntry::MethodHandle(_) => {
                    // TODO: Validate this once we figure out other data structures
                }
                ConstantEntry::MethodType(data) => {
                    data.descriptor.try_resolve()?;
                }
                ConstantEntry::Dynamic(_) => todo!(),
                ConstantEntry::InvokeDynamic(data) => {
                    // TODO: Validate data.method_index once we figure out that implementation
                    data.name_and_type.try_resolve()?;
                }
                ConstantEntry::Package(_) => todo!(),
                ConstantEntry::Reserved => {}
            }
        }
        Ok(())
    }
}

#[derive(Debug, Clone, Copy)]
pub enum ConstantTag {
    Class,
    Field,
    Method,
    InterfaceMethod,
    String,
    Integer,
    Float,
    Long,
    Double,
    NameAndType,
    Utf8,
    MethodHandle,
    MethodType,
    Dynamic,
    InvokeDynamic,
    Module,
    Package,
}

impl ConstantTag {
    pub fn from_tag(tag: u8) -> Self {
        match tag {
            1 => ConstantTag::Utf8,
            3 => ConstantTag::Integer,
            4 => ConstantTag::Float,
            5 => ConstantTag::Long,
            6 => ConstantTag::Double,
            7 => ConstantTag::Class,
            8 => ConstantTag::String,
            9 => ConstantTag::Field,
            10 => ConstantTag::Method,
            11 => ConstantTag::InterfaceMethod,
            12 => ConstantTag::NameAndType,
            15 => ConstantTag::MethodHandle,
            16 => ConstantTag::MethodType,
            17 => ConstantTag::Dynamic,
            18 => ConstantTag::InvokeDynamic,
            19 => ConstantTag::Method,
            20 => ConstantTag::Package,
            _ => todo!("{} is an unknown tag", tag),
        }
    }
}

#[derive(Debug, Clone)]
pub struct ConstantClass {
    pub tag: ConstantTag,
    pub name: Addressed<ConstantUtf8>,
}

#[derive(Debug, Clone)]
pub struct ConstantField {
    pub tag: ConstantTag,
    pub class: Addressed<ConstantClass>,
    pub name_and_type: Addressed<ConstantNameAndType>,
}

#[derive(Debug, Clone)]
pub struct ConstantMethod {
    pub tag: ConstantTag,
    pub class: Addressed<ConstantClass>,
    pub name_and_type: Addressed<ConstantNameAndType>,
}

#[derive(Debug, Clone)]
pub struct ConstantInterfaceMethod {
    pub tag: ConstantTag,
    pub class: Addressed<ConstantClass>,
    pub name_and_type: Addressed<ConstantNameAndType>,
}
#[derive(Debug, Clone)]
pub struct ConstantString {
    pub tag: ConstantTag,
    pub string: Addressed<ConstantUtf8>,
}
#[derive(Debug, Clone)]
pub struct ConstantInteger {
    pub tag: ConstantTag,
    pub bytes: u32,
}

#[derive(Debug, Clone)]
pub struct ConstantFloat {
    pub tag: ConstantTag,
    pub bytes: f32,
}

#[derive(Debug, Clone)]
pub struct ConstantLong {
    pub tag: ConstantTag,
    pub bytes: u64,
}

#[derive(Debug, Clone)]
pub struct ConstantDouble {
    pub tag: ConstantTag,
    pub bytes: f64,
}
#[derive(Debug, Clone)]
pub struct ConstantNameAndType {
    pub tag: ConstantTag,
    pub name: Addressed<ConstantUtf8>,
    pub descriptor: Addressed<ConstantUtf8>,
}

#[derive(Debug, Clone)]
pub struct ConstantUtf8 {
    pub tag: ConstantTag,
    pub length: u16,
    pub bytes: Vec<u8>,
}

#[derive(Debug, Clone)]
pub struct ConstantMethodHandle {
    pub tag: ConstantTag,
    pub kind: u8,
    pub index: u16,
}
#[derive(Debug, Clone)]
pub struct ConstantMethodType {
    pub tag: ConstantTag,
    pub descriptor: Addressed<ConstantUtf8>,
}

#[derive(Debug, Clone)]
pub struct ConstantDynamic {
    pub tag: ConstantTag,
    pub method_index: u16,
    pub name_and_type: Addressed<ConstantNameAndType>,
}

#[derive(Debug, Clone)]
pub struct ConstantInvokeDynamic {
    pub tag: ConstantTag,
    pub method_index: u16,
    pub name_and_type: Addressed<ConstantNameAndType>,
}

#[derive(Debug, Clone)]
pub struct ConstantPackage {
    pub tag: ConstantTag,
    pub name: Addressed<ConstantUtf8>,
}

// TODO: pretty sure these need to use a utf8 variant
impl ConstantUtf8 {
    pub fn string(self) -> String {
        String::from_utf8(self.bytes).unwrap()
    }

    pub fn try_string(self) -> Result<String> {
        Ok(String::from_utf8(self.bytes)?)
    }
}

impl ConstantString {
    pub fn string(&self) -> String {
        String::from_utf8_lossy(&self.string.resolve().bytes).to_string()
    }

    pub fn try_string(&self) -> Result<String> {
        Ok(String::from_utf8(self.string.try_resolve()?.bytes)?)
    }
}

#[derive(EnumAsInner, Clone, Debug)]
pub enum ConstantEntry {
    Class(ConstantClass),
    Field(ConstantField),
    Method(ConstantMethod),
    InterfaceMethod(ConstantInterfaceMethod),
    String(ConstantString),
    Integer(ConstantInteger),
    Float(ConstantFloat),
    Long(ConstantLong),
    Double(ConstantDouble),
    NameAndType(ConstantNameAndType),
    Utf8(ConstantUtf8),
    MethodHandle(ConstantMethodHandle),
    MethodType(ConstantMethodType),
    Dynamic(ConstantDynamic),
    InvokeDynamic(ConstantInvokeDynamic),
    Package(ConstantPackage),
    Reserved,
}

#[cfg(test)]
mod tests {}