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
use crate::instruction::{Instruction, Operand};
use super::super::{HighLevelEmitter, LiteralValue};
const MAX_INTERNAL_CALL_ENTRY_DELTA: usize = 16;
impl HighLevelEmitter {
fn normalize_internal_call_target(&self, target: usize) -> usize {
if self.method_labels_by_offset.contains_key(&target)
|| self.method_arg_counts_by_offset.contains_key(&target)
{
return target;
}
if let Some((candidate, _)) = self
.method_arg_counts_by_offset
.range(..=target)
.next_back()
{
if target.saturating_sub(*candidate) <= MAX_INTERNAL_CALL_ENTRY_DELTA
&& self
.method_labels_by_offset
.get(candidate)
.map(|label| label.as_str() != "script_entry")
.unwrap_or(false)
{
return *candidate;
}
}
if let Some((candidate, label)) = self.method_labels_by_offset.range(..=target).next_back()
{
if target.saturating_sub(*candidate) <= MAX_INTERNAL_CALL_ENTRY_DELTA
&& label.as_str() != "script_entry"
{
return *candidate;
}
}
target
}
fn resolve_internal_call_name(&self, target: usize) -> Option<&str> {
self.method_labels_by_offset
.get(&target)
.map(std::string::String::as_str)
}
fn emit_internal_call(&mut self, instruction: &Instruction, target: usize) {
let mut target = self.normalize_internal_call_target(target);
if let Some(required_args) = self.method_arg_counts_by_offset.get(&target).copied() {
if self.stack.len() < required_args {
if let Some((candidate, _)) =
self.method_arg_counts_by_offset.range(..target).rev().find(
|(candidate, candidate_args)| {
target.saturating_sub(**candidate) <= MAX_INTERNAL_CALL_ENTRY_DELTA
&& **candidate_args <= self.stack.len()
&& self
.method_labels_by_offset
.get(*candidate)
.map(|label| label.as_str() != "script_entry")
.unwrap_or(false)
},
)
{
target = *candidate;
}
}
}
let callee = self
.resolve_internal_call_name(target)
.map(str::to_string)
.unwrap_or_else(|| format!("call_0x{target:04X}"));
if let Some(arg_count) = self.method_arg_counts_by_offset.get(&target).copied() {
self.push_comment(instruction);
if self.stack.len() < arg_count {
self.stack_underflow(instruction, arg_count);
return;
}
let mut args = Vec::with_capacity(arg_count);
for _ in 0..arg_count {
if let Some(value) = self.pop_stack_value() {
// Internal calls use right-to-left push order (C convention),
// so popping yields arguments in correct left-to-right display order.
args.push(value);
}
}
let args = args.join(", ");
let temp = self.next_temp();
self.statements
.push(format!("let {temp} = {callee}({args});"));
self.stack.push(temp);
return;
}
self.push_comment(instruction);
let temp = self.next_temp();
self.statements.push(format!("let {temp} = {callee}();"));
self.stack.push(temp);
}
pub(in super::super) fn emit_relative_call(&mut self, instruction: &Instruction) {
if let Some(target) = self.jump_target(instruction) {
let resolved_target = self
.call_targets_by_offset
.get(&instruction.offset)
.copied()
.unwrap_or(target);
self.emit_internal_call(instruction, resolved_target);
} else if let Some(target) = self
.call_targets_by_offset
.get(&instruction.offset)
.copied()
{
self.emit_internal_call(instruction, target);
} else {
self.warn(instruction, "call with unsupported operand (skipping)");
}
}
pub(in super::super) fn emit_relative(&mut self, instruction: &Instruction, label: &str) {
if self.skip_jumps.remove(&instruction.offset) {
return;
}
if let Some(target) = self.jump_target(instruction) {
self.warn(
instruction,
&format!("{label} -> 0x{target:04X} (control flow not yet lifted)"),
);
} else {
self.warn(
instruction,
&format!("{label} with unsupported operand (skipping)"),
);
}
}
pub(in super::super) fn emit_indirect_call(&mut self, instruction: &Instruction, label: &str) {
match instruction.operand {
Some(Operand::U16(value)) => {
// CALLT: token-based indirect call with a U16 operand.
// Resolve token metadata so argument consumption and return
// behavior match the declared method signature.
let index = value as usize;
let resolved = self.callt_labels.get(index).cloned();
if let Some(name) = resolved {
let arg_count = self.callt_param_counts.get(index).copied().unwrap_or(0);
let returns_value =
self.callt_returns_value.get(index).copied().unwrap_or(true);
self.push_comment(instruction);
// Always emit the token call — even if the evaluation
// stack doesn't carry enough values (e.g. malformed
// bytecode, or a missed lift earlier in the method).
// Earlier this branch dropped the call entirely on
// underflow and just emitted a structured warning,
// leaving the rendered source missing the CALLT
// entirely; the JS port has always substituted `???`
// for missing args and emitted the call shape so the
// reader can see what was attempted.
if self.stack.len() < arg_count {
self.stack_underflow(instruction, arg_count);
}
// Internal calls (and CALLT) use right-to-left push
// order (C convention), so popping yields arguments
// in correct left-to-right display order — no
// reverse needed before joining.
let mut args = Vec::with_capacity(arg_count);
for _ in 0..arg_count {
if let Some(value) = self.pop_stack_value() {
args.push(value);
} else {
args.push("???".to_string());
}
}
let args = args.join(", ");
if returns_value {
let temp = self.next_temp();
self.statements
.push(format!("let {temp} = {name}({args});"));
self.stack.push(temp);
} else {
self.statements.push(format!("{name}({args});"));
}
} else {
self.push_comment(instruction);
let temp = self.next_temp();
self.statements
.push(format!("let {temp} = {label}(0x{value:04X});"));
self.stack.push(temp);
}
}
None => {
// CALLA: stack-based indirect call — pops a Pointer from the
// evaluation stack, so consume one stack entry as the target.
let (target, literal) = self
.pop_stack_value_with_literal()
.unwrap_or_else(|| ("??".to_string(), None));
if let Some(LiteralValue::Pointer(offset)) = literal {
self.emit_internal_call(instruction, offset);
} else if let Some(offset) = self
.calla_targets_by_offset
.get(&instruction.offset)
.copied()
{
self.emit_internal_call(instruction, offset);
} else {
self.push_comment(instruction);
let temp = self.next_temp();
self.statements
.push(format!("let {temp} = {label}({target});"));
self.stack.push(temp);
}
}
_ => self.warn(instruction, &format!("{label} (unexpected operand)")),
}
}
pub(in super::super) fn emit_jump(&mut self, instruction: &Instruction) {
if self.skip_jumps.remove(&instruction.offset) {
// jump consumed by structured if/else handling
return;
}
match self.jump_target(instruction) {
Some(target) => {
if self.try_emit_loop_jump(instruction, target) {
return;
}
// Tail-call: JMP to a known method entry point.
if self.method_labels_by_offset.contains_key(&target) {
self.emit_internal_call(instruction, target);
let result = self.stack.pop().unwrap_or_default();
if result.is_empty() {
self.statements.push("return;".into());
} else {
self.statements.push(format!("return {result};"));
}
return;
}
self.push_comment(instruction);
if self.index_by_offset.contains_key(&target) {
self.transfer_labels.insert(target);
}
self.statements
.push(format!("goto {};", Self::transfer_label_name(target)));
}
None => self.warn(instruction, "jump with unsupported operand (skipping)"),
}
}
pub(in super::super) fn emit_endtry(&mut self, instruction: &Instruction) {
if self.skip_jumps.remove(&instruction.offset) {
return;
}
self.push_comment(instruction);
match self.jump_target(instruction) {
Some(target) => {
// When an ENDTRY targets a loop's continue offset, it acts
// as `continue` — the VM executes the finally block first,
// then resumes at the loop condition.
if self
.loop_stack
.iter()
.rev()
.any(|ctx| target == ctx.continue_offset)
{
self.statements.push("continue;".into());
return;
}
// When an ENDTRY targets at or beyond a loop's break offset,
// it acts as a `break` — exiting both the try block and the
// enclosing loop.
if self
.loop_stack
.iter()
.rev()
.any(|ctx| target >= ctx.break_offset)
{
self.statements.push("break;".into());
return;
}
if self.index_by_offset.contains_key(&target) {
self.transfer_labels.insert(target);
}
self.statements
.push(format!("leave {};", Self::transfer_label_name(target)));
}
None => self.warn(instruction, "end-try with unsupported operand (skipping)"),
}
}
}